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

import {
	authType,
} from '../../assets/data';
import { Title, FormWrapper} from '../../styles/Components';
import {
	Pagination,
	 CaliTable, TableHeader,
} from '../../components/common';
import { convertKTC, timeDiffMinute } from '../../utils';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { useModal, useTable, withAuth } from '../../hooks/hook';
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'
import { CommonSearchBar, useCommonSearch } from '../../components/ServiceManage';
import { useAlert } from '../../context/AlertProvider';
import { alertTypes } from '../../assets/data/types';
import { useLoading } from '../../context/LoadingProvider';
import useEnhancedCommonSearch from '../../hooks/useEnhancedCommonSearch';

const MenuBanner = () => {
	const tableRef = useRef(null);
	const navigate = useNavigate();
	const { showToast, showModal } = useAlert();
	const {withLoading} = useLoading();
	const token = sessionStorage.getItem('token');

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

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

	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handleOrderByChange,
		updateSearchParams,
		loading,
		configLoaded,
		paginationType,
		pagination,
		goToNextPage,
		goToPrevPage,
		handlePageChange,
		handlePageSizeChange
	} = useEnhancedCommonSearch("menuBannerSearch");

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

	const handleAction = async (action, item = null) => {
		switch (action) {
			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){
					showToast('LAND_AUCTION_DELETE_DATE_WARNING', {type: alertTypes.warning});
					return;
				}
				showModal('MENU_BANNER_SELECT_DELETE', {
					type: alertTypes.confirm,
					onConfirm: () => handleAction('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) {
					showToast('LAND_AUCTION_WARNING_DELETE', {type: alertTypes.warning});
					return;
				}

				await withLoading(async () => {
					return await MenuBannerDelete(token, list);
				}).then(data => {
					if(data.result === "SUCCESS") {
						showToast('DEL_COMPLETE', {type: alertTypes.success});
						// handleSearch();
						// window.location.reload();
					}else if(data.result === "ERROR_AUCTION_STATUS_IMPOSSIBLE"){
						showToast('LAND_AUCTION_ERROR_DELETE_STATUS', {type: alertTypes.error});
					}else{
						showToast('DELETE_FAIL', {type: alertTypes.error});
					}
				}).catch(reason => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleSearch(updateSearchParams);
				});

				break;

			default:
				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}
				refProp={tableRef}
				loading={loading}
				isRowSelected={isRowSelected}
			/>

			{/* 페이징 */}
			<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}
			/>

		</>
	)
};

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