import React, { Fragment, useCallback, useState } from 'react';

import { CommonSearchBar } from '../../components/ServiceManage';
import { Title, FormWrapper } from '../../styles/Components';
import { authType } from '../../assets/data';
import { useModal, withAuth } from '../../hooks/hook';
import { CaliTable } from '../../components/common';
import tableInfo from '../../assets/data/pages/historyTable.json';
import useEnhancedCommonSearch from '../../hooks/useEnhancedCommonSearch';
import FrontPagination from '../../components/common/Pagination/FrontPagination';
import { INITIAL_CURRENT_PAGE, INITIAL_PAGE_LIMIT, INITIAL_PAGE_SIZE } from '../../assets/data/adminConstants';
import LogDetailModal from '../../components/common/modal/LogDetailModal';

const LogView = () => {
	const [detailData, setDetailData] = useState({});
	const [currentPage, setCurrentPage] = useState(INITIAL_CURRENT_PAGE);
	const [displayData, setDisplayData] = useState([]);

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

	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		updateSearchParams,
		loading
	} = useEnhancedCommonSearch("historySearch");

	const handleClientPageChange = useCallback((slicedData) => {
		setDisplayData(slicedData);
	}, []);

	const handleAction = async (action, item = null) => {
		switch (action) {
			case "detail":
				handleModalView('detail');
				setDetailData(item.data);
				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>

			{/* 조회테이블 */}
			<CaliTable
				columns={tableInfo.columns}
				data={displayData}
				onAction={(action, item) => handleAction(action, item)}
				// refProp={tableRef}
				loading={loading}
			/>

			{/* 페이징 */}
			{dataList?.list &&
				<FrontPagination
					data={dataList.list}
					itemsPerPage={INITIAL_PAGE_SIZE}
					currentPage={currentPage}
					setCurrentPage={setCurrentPage}
					pageLimit={INITIAL_PAGE_LIMIT}
					onPageChange={handleClientPageChange}
				/>}

			{/* 상세 */}
			<LogDetailModal
				viewMode="data"
				detailView={modalState.detailModal}
				handleDetailView={() => handleModalClose('detail')}
				detailData={detailData}
				title="상세정보"
			/>

		</>
	);
};

export default withAuth(authType.adminLogSearchRead)(LogView);
