import { useState, Fragment, useRef } from 'react';
import { useRecoilValue } from 'recoil';
import { useTranslation } from 'react-i18next';
import 'react-datepicker/dist/react-datepicker.css';

import { authList } from '../../store/authList';
import {
	authType,
	modalTypes,
	landAuctionStatusType, opYNType,
} from '../../assets/data';
import { Title, FormWrapper, TableStyle, TableWrapper} from '../../styles/Components';
import {
	CheckBox,
	Button,
	DynamicModal,
	Pagination,
	ViewTableInfo, CaliTable, TableHeader,
} from '../../components/common';
import { convertKTC, timeDiffMinute } from '../../utils';
import { INITIAL_PAGE_SIZE, INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { StatusWapper, StatusLabel } from '../../styles/ModuleComponents';
import { opMenuBannerStatus } from '../../assets/data/options';
import MenuBannerSearchBar, { useMenuBannerSearch } from '../../components/ServiceManage/searchBar/MenuBannerSearchBar';
import { MenuBannerDelete, MenuBannerDetailView } from '../../apis';
import { useNavigate } from 'react-router-dom';
import MenuBannerModal from '../../components/ServiceManage/modal/MenuBannerModal';
import tableInfo from '../../assets/data/pages/menuBannerTable.json'

const MenuBanner = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const tableRef = useRef(null);
	const navigate = useNavigate();

	const [detailData, setDetailData] = useState({});

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		deleteConfirm: 'hidden',
		deleteComplete: 'hidden'
	});
	const [alertMsg, setAlertMsg] = useState('');
	const [modalType, setModalType] = useState('regist');

	const {
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams
	} = useMenuBannerSearch(token, INITIAL_PAGE_SIZE);

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


	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "regist":
				setModalType('regist');
				handleModalView('detail');
				break;
			case "detail":
				await MenuBannerDetailView(token, param).then(data => {
					setDetailData(data.event_detail);
					setModalType('modify');
					handleModalView('detail');
				});
				break;
			case "delete":
				const date_check = selectedRows.every(row => {
					const timeDiff = timeDiffMinute(convertKTC(row.auction_start_dt), (new Date));
					return timeDiff < 3;
				});
				if(date_check){
					setAlertMsg(t('LAND_AUCTION_DELETE_DATE_WARNING'));
					return;
				}
				if(selectedRows[0].status === landAuctionStatusType.auction_start || selectedRows[0].status === landAuctionStatusType.stl_end){
					setAlertMsg(t('LAND_AUCTION_DELETE_STATUS_WARNING'));
					return;
				}
				handleModalView('deleteConfirm');
				break;
			case "deleteConfirm":
				let list = [];
				let isChecked = false;

				selectedRows.map(data => {
					// const row = dataList.list.find(row => row.id === Number(data.id));
					// if(row.status !== commonStatus.wait) isChecked = true;
					list.push({
						id: data.id,
					});
				});

				if(isChecked) {
					setAlertMsg(t('LAND_AUCTION_WARNING_DELETE'))
					handleModalClose('deleteConfirm');
					return;
				}

				await MenuBannerDelete(token, list).then(data => {
					handleModalClose('deleteConfirm');
					if(data.result === "SUCCESS") {
						handleModalView('deleteComplete');
					}else if(data.result === "ERROR_AUCTION_STATUS_IMPOSSIBLE"){
						setAlertMsg(t('LAND_AUCTION_ERROR_DELETE_STATUS'));
					}else{
						setAlertMsg(t('DELETE_FAIL'));
					}
				}).catch(reason => {
					setAlertMsg(t('API_FAIL'));
				});

				break;
			case "deleteComplete":
				handleModalClose('deleteComplete');
				window.location.reload();
				break;
			case "warning":
				setAlertMsg('')
				break;
		}
	}

	const handleAction = async (action, item = null) => {
		switch (action) {
			case "regist":
				setModalType('regist');
				handleModalView('detail');
				break;
			case "detail":
				await MenuBannerDetailView(token, item).then(data => {
					setDetailData(data.event_detail);
					setModalType('modify');
					handleModalView('detail');
				});
				break;
			case "delete":
				const date_check = selectedRows.every(row => {
					const timeDiff = timeDiffMinute(convertKTC(row.auction_start_dt), (new Date));
					return timeDiff < 3;
				});
				if(date_check){
					setAlertMsg(t('LAND_AUCTION_DELETE_DATE_WARNING'));
					return;
				}
				if(selectedRows[0].status === landAuctionStatusType.auction_start || selectedRows[0].status === landAuctionStatusType.stl_end){
					setAlertMsg(t('LAND_AUCTION_DELETE_STATUS_WARNING'));
					return;
				}
				handleModalView('deleteConfirm');
				break;
			case "deleteConfirm":
				let list = [];
				let isChecked = false;

				selectedRows.map(data => {
					// const row = dataList.list.find(row => row.id === Number(data.id));
					// if(row.status !== commonStatus.wait) isChecked = true;
					list.push({
						id: data.id,
					});
				});

				if(isChecked) {
					setAlertMsg(t('LAND_AUCTION_WARNING_DELETE'))
					handleModalClose('deleteConfirm');
					return;
				}

				await MenuBannerDelete(token, list).then(data => {
					handleModalClose('deleteConfirm');
					if(data.result === "SUCCESS") {
						handleModalView('deleteComplete');
					}else if(data.result === "ERROR_AUCTION_STATUS_IMPOSSIBLE"){
						setAlertMsg(t('LAND_AUCTION_ERROR_DELETE_STATUS'));
					}else{
						setAlertMsg(t('DELETE_FAIL'));
					}
				}).catch(reason => {
					setAlertMsg(t('API_FAIL'));
				});

				break;
			case "deleteComplete":
				handleModalClose('deleteComplete');
				window.location.reload();
				break;
			case "warning":
				setAlertMsg('')
				break;

			default:
				break;
		}
	};

	return (
		<>
			<Title>메뉴 배너 관리</Title>
			<FormWrapper>
				<MenuBannerSearchBar
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>
			{/*<ViewTableInfo total={dataList?.total} total_all={dataList?.total_all} handleOrderBy={handleOrderByChange} handlePageSize={handlePageSizeChange}>*/}
			{/*	{userInfo.auth_list?.some(auth => auth.id === authType.battleEventDelete) && (*/}
			{/*		<Button theme={selectedRows.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={() => handleModalSubmit('delete')} />*/}
			{/*	)}*/}
			{/*	{userInfo.auth_list?.some(auth => auth.id === authType.battleEventUpdate) && (*/}
			{/*		<Button*/}
			{/*			theme="primary"*/}
			{/*			text="이미지 등록"*/}
			{/*			type="button"*/}
			{/*			handleClick={e => {*/}
			{/*				e.preventDefault();*/}
			{/*				navigate('/servicemanage/menubanner/menubannerregist');*/}
			{/*			}}*/}
			{/*		/>*/}
			{/*	)}*/}
			{/*</ViewTableInfo>*/}
			<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}
				refProp={tableRef}
			/>

			{/*<TableWrapper>*/}
			{/*	<TableStyle ref={tableRef}>*/}
			{/*		<caption></caption>*/}
			{/*		<thead>*/}
			{/*		<tr>*/}
			{/*			<th width="40"></th>*/}
			{/*			<th width="70">번호</th>*/}
			{/*			<th width="80">등록 상태</th>*/}
			{/*			<th width="150">시작일(KST)</th>*/}
			{/*			<th width="150">종료일(KST)</th>*/}
			{/*			<th width="300">설명 제목</th>*/}
			{/*			<th width="90">링크여부</th>*/}
			{/*			<th width="100">상세보기</th>*/}
			{/*			<th width="150">히스토리</th>*/}
			{/*		</tr>*/}
			{/*		</thead>*/}
			{/*		<tbody>*/}
			{/*		{dataList?.list?.map(banner => (*/}
			{/*					<tr key={banner.row_num}>*/}
			{/*						<td>*/}
			{/*							<CheckBox name={'select'} id={banner.id}*/}
			{/*									  setData={(e) => handleSelectRow(e, banner)}*/}
			{/*									  checked={isRowSelected(banner.id)} />*/}
			{/*						</td>*/}
			{/*						<td>{banner.row_num}</td>*/}
			{/*						<StatusWapper>*/}
			{/*							<StatusLabel $status={banner.status}>*/}
			{/*								{opMenuBannerStatus.find(data => data.value === banner.status)?.name}*/}
			{/*							</StatusLabel>*/}
			{/*						</StatusWapper>*/}
			{/*						<td>{convertKTC(banner.start_dt)}</td>*/}
			{/*						<td>{convertKTC(banner.end_dt)}</td>*/}
			{/*						<td>{banner.title}</td>*/}
			{/*						<td>{opYNType.find(data => data.value === banner.is_link)?.name}</td>*/}
			{/*						<td>*/}
			{/*							<Button theme="line" text="상세보기"*/}
			{/*									handleClick={e => handleModalSubmit('detail', banner.id)} />*/}
			{/*						</td>*/}
			{/*						<td>{banner.update_by}</td>*/}
			{/*					</tr>*/}
			{/*			))}*/}
			{/*		</tbody>*/}
			{/*	</TableStyle>*/}
			{/*</TableWrapper>*/}

			<Pagination postsPerPage={searchParams.pageSize} totalPosts={dataList?.total_all} setCurrentPage={handlePageChange} currentPage={searchParams.currentPage} pageLimit={INITIAL_PAGE_LIMIT} />

			{/*상세*/}
			<MenuBannerModal modalType={modalType} detailView={modalState.detailModal} handleDetailView={() => handleModalClose('detail')} content={detailData} setDetailData={setDetailData} />

			{/*삭제 확인*/}
			<DynamicModal
				modalType={modalTypes.confirmOkCancel}
				view={modalState.deleteConfirmModal}
				handleCancel={() => handleModalClose('deleteConfirm')}
				handleSubmit={() => handleModalSubmit('deleteConfirm')}
				modalText={t('MENU_BANNER_SELECT_DELETE')}
			/>
			{/*삭제 완료*/}
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.deleteCompleteModal}
				handleSubmit={() => handleModalSubmit('deleteComplete')}
				modalText={t('DEL_COMPLETE')}
			/>
			{/* 경고 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={alertMsg ? 'view' : 'hidden'}
				modalText={alertMsg}
				handleSubmit={() => handleModalSubmit('warning')}
			/>
		</>
	)
};

export default withAuth(authType.battleEventRead)(MenuBanner);
