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

import {
	authType, commonStatus as CommonStatus,
} from '../../assets/data';
import { Title, FormWrapper} from '../../styles/Components';
import {
	Pagination,
	 CaliTable, TableHeader,
} from '../../components/common';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { LogHistory, MenuBannerDelete, MenuBannerDetailView } from '../../apis';
import { useNavigate } from 'react-router-dom';
import tableInfo from '../../assets/data/pages/menuBannerTable.json'
import { CommonSearchBar } from '../../components/ServiceManage';
import { useAlert } from '../../context/AlertProvider';
import { alertTypes } from '../../assets/data/types';
import { useLoading } from '../../context/LoadingProvider';
import useEnhancedCommonSearch from '../../hooks/useEnhancedCommonSearch';
import MenuBannerDetailModal from '../../components/modal/MenuBannerDetailModal';
import { historyTables } from '../../assets/data/data';
import LogDetailModal from '../../components/common/modal/LogDetailModal';
import { AnimatedPageWrapper } from '../../components/common/Layout';

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 [historyData, setHistoryData] = useState({});

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		history: 'hidden',
	});

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

	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.event_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.menuBanner

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					handleModalView('history');
				});
				break;
			case "detail":
				await MenuBannerDetailView(token, item.id).then(data => {
					setDetailData(data.detail);
					handleModalView('detail');
				});
				break;
			case "delete":

				showModal('MENU_BANNER_SELECT_DELETE', {
					type: alertTypes.confirm,
					onConfirm: () => handleAction('deleteConfirm')
				});
				break;
			case "deleteConfirm":
				const low = selectedRows[0];

				if(low.status !== CommonStatus.wait) {
					showToast('DELETE_STATUS_ONLY_WAIT', {type: alertTypes.warning});
					return;
				}

				await withLoading(async () => {
					return await MenuBannerDelete(token, low.id);
				}).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 (
		<AnimatedPageWrapper>
			<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}
			/>

			{/* 상세 */}
			<MenuBannerDetailModal
				detailView={modalState.detailModal}
				handleDetailView={() => {
					handleModalClose('detail');
					handleSearch(updateSearchParams);
				}}
				content={detailData}
				setDetailData={setDetailData}
			/>

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

		</AnimatedPageWrapper>
	)
};

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