import React, { useState, Fragment, useMemo } from 'react';
import Button from '../../components/common/button/Button';
import Loading from '../../components/common/Loading';

import {
	Title,
	SelectInput,
	TableStyle,
	TableWrapper,
	TableActionButton,
	TableDetailRow,
	TableDetailContainer,
	TableDetailFlex,
	TableDetailColumn,
	DetailTableInfo,
} from '../../styles/Components';

import { modalTypes } from '../../assets/data';

import { useTranslation } from 'react-i18next';
import {
	FormLabel,
	FormRowGroup, MessageWrapper,
} from '../../styles/ModuleComponents';
import { authType } from '../../assets/data';
import { useModal, withAuth } from '../../hooks/hook';
import { DynamicModal, TopButton } from '../../components/common';
import { opInitDataType, opSuccessType } from '../../assets/data/options';
import { InitData } from '../../apis/Data';
import DataInitSearchBar, { useDataInitSearch } from '../../components/ServiceManage/searchBar/DataInitSearchBar';

const DataInitView = () => {
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');

	const [loading, setLoading] = useState(false);		// 로딩 창
	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		cancel: 'hidden',
		registConfirm: 'hidden',
		registComplete: 'hidden'
	});

	const [alertMsg, setAlertMsg] = useState('');

	const [resultData, setResultData] = useState(initData);	//데이터 정보
	const [expandedRows, setExpandedRows] = useState({});

	const {
		searchParams,
		loading: dataLoading,
		data: dataList,
		handleSearch,
		handleReset,
		updateSearchParams
	} = useDataInitSearch(token, setAlertMsg);

	const toggleRowExpand = (index) => {
		setExpandedRows(prev => ({
			...prev,
			[index]: !prev[index]
		}));
	};

	const tableHeaders = useMemo(() => {
		return [
			{ id: 'logTime', label: '일시', width: '100px' },
			{ id: 'key', label: '키', width: '150px' },
			{ id: 'dataType', label: '초기화대상', width: '80px' },
			{ id: 'tranId', label: '트랜잭션ID', width: '150px' },
			{ id: 'success', label: '성공여부', width: '60px' },
			{ id: 'message', label: '작업메시지', width: '300px' },
			{ id: 'details', label: '상세정보', width: '100px' },
			// { id: 'recovery', label: '복구', width: '100px' }
		];
	}, []);

	const renderDetailData = (data) => {
		if (!data || typeof data !== 'object') return <></>;

		return (
			<DetailTableInfo>
				<thead>
				<tr>
					<th colSpan="2">정보</th>
				</tr>
				</thead>
				<tbody>
				{Object.entries(data).map(([key, value]) => (
					<tr key={`${key}`}>
						<td>{key}</td>
						<td>
							{typeof value === 'object' && value !== null
								? JSON.stringify(value)
								: String(value)
							}
						</td>
					</tr>
				))}
				</tbody>
			</DetailTableInfo>
		);
	};

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "submit":
				handleModalView('registConfirm');
				break;
			case "registConfirm":
				setLoading(true);

				await InitData(token, resultData).then(data => {
					handleModalClose('registConfirm');
					if(data.result === "SUCCESS") {
						handleModalView('registComplete');
					}else{
						setAlertMsg(t('REGIST_FAIL'));
					}
				}).catch(reason => {
					handleModalClose('registConfirm');
					setAlertMsg(t('API_FAIL'));
				}).finally(() => {
					setLoading(false);
				});

				break;
			case "registComplete":
				dataReset();
				handleModalClose('registComplete');
				break;
			case "warning":
				setAlertMsg('');
				break;
		}
	}

	const dataReset = () => {
		setResultData(initData);
	}

	return (
		<>
			<Title>데이터 초기화</Title>
			<MessageWrapper>
				<FormRowGroup>
					<FormLabel>초기화 대상</FormLabel>
					<SelectInput value={resultData?.init_data_type} onChange={e => setResultData({ ...resultData, init_data_type: e.target.value })} width="150px">
						{opInitDataType.map((data, index) => (
							<option key={index} value={data.value}>
								{data.name}
							</option>
						))}
					</SelectInput>
					<Button
						text="초기화"
						theme={'primary'}
						type="submit"
						size="large"
						width="100px"
						handleClick={() => handleSubmit('submit')}
					/>
				</FormRowGroup>
			</MessageWrapper>
			<MessageWrapper>
				<DataInitSearchBar
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</MessageWrapper>
			<TableWrapper>
				<TableStyle>
					<thead>
					<tr>
						{tableHeaders.map(header => (
							<th key={header.id} width={header.width}>{header.label}</th>
						))}
					</tr>
					</thead>
					<tbody>
					{dataList?.init_list?.map((item, index) => (
						<Fragment key={index}>
							<tr>
								<td>{item.timestamp}</td>
								<td>{item.key}</td>
								<td>{opInitDataType.find(type => type.value === item.initDataType)?.name}</td>
								<td>{item.tranId}</td>
								<td>{opSuccessType.find(type => type.value === item.success)?.name}</td>
								<td>{item.message}</td>
								<td>
									<TableActionButton onClick={() => toggleRowExpand(index)}>
										{expandedRows[index] ? '접기' : '상세보기'}
									</TableActionButton>
								</td>
							</tr>
							{expandedRows[index] && (
								<TableDetailRow>
									<td colSpan={tableHeaders.length}>
										<TableDetailContainer>
											<TableDetailFlex>
												<TableDetailColumn>
													{renderDetailData(item.data)}
												</TableDetailColumn>
											</TableDetailFlex>
										</TableDetailContainer>
									</td>
								</TableDetailRow>
							)}
						</Fragment>
					))}
					</tbody>
				</TableStyle>
			</TableWrapper>

			{/* 확인 모달 */}
			<DynamicModal
				modalType={modalTypes.confirmOkCancel}
				view={modalState.registConfirmModal}
				modalText={t('DATA_INIT_CONFIRM',{data:opInitDataType.find(type => type.value === resultData.init_data_type).name})}
				handleSubmit={() => handleSubmit('registConfirm')}
				handleCancel={() => handleModalClose('registConfirm')}
			/>
			{/* 완료 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.registCompleteModal}
				modalText={t('INIT_COMPLTE')}
				handleSubmit={() => handleSubmit('registComplete')}
			/>
			{/* 경고 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={alertMsg ? 'view' : 'hidden'}
				modalText={alertMsg}
				handleSubmit={() => setAlertMsg('')}
			/>
			{(loading || dataLoading) && <Loading/>}
			<TopButton />
		</>
	);
};

export default withAuth(authType.levelMaster)(DataInitView);

const initData = {
	init_data_type: 'None'
}
