import React, { useState, Fragment } from 'react';
import { Title, FormWrapper, TextInput } from '../../styles/Components';
import { useNavigate } from 'react-router-dom';
import {
	CommonSearchBar,
	UserBlockDetailModal,
} from '../../components/ServiceManage/';
import { BlackListDetail, BlackListDelete, LogHistory } from '../../apis';
import Pagination from '../../components/common/Pagination/Pagination';

import { authType, commonStatus, modalTypes } from '../../assets/data';
import { CaliTable, TableHeader } from '../../components/common';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { alertTypes, customStatus } from '../../assets/data/types';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import tableInfo from '../../assets/data/pages/userBlockTable.json'
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import useCommonSearchOld from '../../hooks/useCommonSearchOld';
import { ModalInputItem, ModalSubText, RegistInputItem } from '../../styles/ModuleComponents';
import DynamicModal from '../../components/common/modal/DynamicModal';
import { useTranslation } from 'react-i18next';
import LogDetailModal from '../../components/common/modal/LogDetailModal';
import { historyTables } from '../../assets/data/data';

const UserBlock = () => {
	const token = sessionStorage.getItem('token');
	const navigate = useNavigate();
	const {showModal, showToast} = useAlert();
	const {withLoading} = useLoading();
	const { t } = useTranslation();

	const [detail, setDetail] = useState([]);
	const [deleteDesc, setDeleteDesc] = useState('');
	const [historyData, setHistoryData] = useState({});
	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		delete: 'hidden',
		history: 'hidden'
	});

	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams,
		loading,
		configLoaded
	} = useCommonSearchOld("userBlockSearch");

	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.list || [], {mode: 'single'});

	const handleAction = async (action, item = null) => {
		switch (action) {
			case "history":
				const params = {};
				params.db_type = "MYSQL"
				params.sql_id = item.id;
				params.table_name = historyTables.userBlock

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					handleModalView('history');
				});
				break;
			case "detail":
				await BlackListDetail(token, item.id).then(data => {
					setDetail(data);
					handleModalView('detail');
				});
				break;
			case "delete":
				const selectRow = selectedRows[0];
				if(selectRow.status === commonStatus.cancel || selectRow.status === customStatus.expiration || selectRow.status === commonStatus.fail) {
					showToast('USER_BLOCK_DELETE_STATUS_WARNING',{type: alertTypes.warning})
					return;
				}
				handleModalView('delete');
				// showModal('USER_BLOCK_DELETE_CONFIRM', {
				// 	type: alertTypes.confirm,
				// 	onConfirm: () => handleAction('deleteConfirm')
				// });
				break;
			case "deleteConfirm":
				let list = [];

				if(deleteDesc.length === 0){
					showToast('INPUT_REASON_EMPTY_WARNING', {type: alertTypes.warning});
					return;
				}

				selectedRows.map(data => {
					list.push({
						id: data.id,
						reason: deleteDesc
					});
				});

				await withLoading(async () => {
					return BlackListDelete(token, list);
				}).then(data => {
					if(data.result === "SUCCESS") {
						showToast('DEL_COMPLETE', {type: alertTypes.success});
					}else{
						showToast(data.data.message, {type: alertTypes.error});
					}
				}).catch(reason => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleModalClose('delete');
					handleSearch(updateSearchParams);
				});

				break;

		}
	};

	return (
		<>
			<Title>이용자 제재 조회 및 등록</Title>
			<FormWrapper>
				<CommonSearchBar
					config={config}
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>
			<TableHeader
				config={tableInfo.header}
				total={dataList?.total}
				total_all={dataList?.total_all}
				handleOrderBy={handleOrderByChange}
				handlePageSize={handlePageSizeChange}
				selectedRows={selectedRows}
				onAction={handleAction}
				navigate={navigate}
			/>
			<CaliTable
				columns={tableInfo.columns}
				data={dataList?.list}
				selectedRows={selectedRows}
				onSelectRow={handleSelectRow}
				onAction={handleAction}
				loading={loading}
				isRowSelected={isRowSelected}
			/>
			<Pagination
				postsPerPage={searchParams.pageSize}
				totalPosts={dataList?.total_all}
				setCurrentPage={handlePageChange}
				currentPage={searchParams.currentPage}
				pageLimit={INITIAL_PAGE_LIMIT}
			/>

			<UserBlockDetailModal
				stateModal={modalState.detailModal}
				data={detail}
				handleModal={() => handleModalClose('detail')}
			/>

			<LogDetailModal
				viewMode="changed"
				detailView={modalState.historyModal}
				handleDetailView={() => handleModalClose('history')}
				changedData={historyData}
				title="히스토리"
			/>

			<DynamicModal
				modalType={modalTypes.childOkCancel}
				view={modalState.deleteModal}
				handleCancel={() => handleModalClose('delete')}
				handleSubmit={() => handleAction('deleteConfirm')}
			>
				<ModalInputItem>
					{t('USER_BLOCK_DELETE_CONFIRM')}
					<RegistInputItem>
						<TextInput
							placeholder="사유 입력"
							maxLength="30"
							value={deleteDesc}
							onChange={e => {
								if (e.target.value.length > 30) return;
								setDeleteDesc(e.target.value.trimStart())
							}}
						/>
					</RegistInputItem>
					<ModalSubText $color={deleteDesc.length > 29 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({deleteDesc.length}/30자)</ModalSubText>
				</ModalInputItem>
			</DynamicModal>
		</>
	);
};

export default withAuth(authType.blackListRead)(UserBlock);
