import { Fragment, useState, useEffect } from 'react';

import LogViewSearchBar from '../../components/UserManage/LogViewSearchBar';
import { Title, FormWrapper, SelectInput, TableInfo, ListCount, ListOption, TableStyle, BtnWrapper, ButtonClose, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import Pagination from '../../components/common/Pagination/Pagination';
import Modal from '../../components/common/modal/Modal';

import LogViewModal from '../../components/UserManage/LogViewModal';

import { LogViewList } from '../../apis';
import { useNavigate } from 'react-router-dom';
import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { logOption } from '../../assets/data';
import { convertKTC } from '../../utils';

const LogView = () => {
	const navigate = useNavigate();
	const userInfo = useRecoilValue(authList);

	const [currentPage, setCurrentPage] = useState(1);

	const [stateModal, setStateModal] = useState('hidden');
	const [dataList, setDataList] = useState([]);
	const [detailData, setDetailData] = useState('');
	const [searchData, setSearchData] = useState({});
	const [orderBy, setOrderBy] = useState('DESC');
	const [pageSize, setPageSize] = useState('50');

	const handleButtonClick = content => {
		setStateModal('view');
		setDetailData(content);
	};

	const handleModal = () => {
		if (stateModal === 'hidden') {
			setStateModal('view');
		} else {
			setStateModal('hidden');
		}
	};

	const handleOrderBy = e => {
		const order = e.target.value;
		setOrderBy(order);
		fetchData(
			searchData.searchOption,
			searchData.data,
			searchData.logOption,
			searchData.startDate && new Date(searchData.startDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			order,
			pageSize,
		);
	};

	const handlePageSize = e => {
		const size = e.target.value;
		setPageSize(size);
		setCurrentPage(1);
		fetchData(
			searchData.searchOption,
			searchData.data,
			searchData.logOption,
			searchData.startDate && new Date(searchData.startDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			orderBy,
			size,
			1,
		);
	};

	const fetchData = async (searchType, searchKey, historyType, startDt, endDt, order, size) => {
		const token = sessionStorage.getItem('token');
		setDataList(await LogViewList(token, searchType, searchKey, historyType, startDt, endDt, order ? order : orderBy, size ? size : pageSize, currentPage));
	};

	useEffect(() => {
		fetchData(
			searchData.searchOption,
			searchData.data,
			searchData.logOption,
			searchData.startDate && new Date(searchData.startDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			orderBy,
			pageSize,
		);
	}, [currentPage]);

	const handleSearch = (searchType, searchKey, historyType, startDt, endDt) => {
		fetchData(searchType, searchKey, historyType, startDt, endDt);
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === 5) ? (
				<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={'view'}>
					<BtnWrapper $justify="flex-end">
						<ButtonClose onClick={() => navigate(-1)} />
					</BtnWrapper>
					<ModalText $align="center">
						해당 메뉴에 대한 조회 권한이 없습니다.
						<br />
						권한 등급을 변경 후 다시 이용해주세요.
					</ModalText>
					<BtnWrapper $gap="10px">
						<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={() => navigate(-1)} />
					</BtnWrapper>
				</Modal>
			) : (
				<>
					<Title>사용 이력 조회</Title>
					<FormWrapper action="" $flow="row">
						<LogViewSearchBar handleSearch={handleSearch} resultData={setSearchData} />
					</FormWrapper>
					<TableInfo>
						<ListCount>
							총 : {dataList && dataList.total} 건 / {dataList && dataList.total_all} 건
						</ListCount>
						<ListOption>
							<SelectInput className="input-select" onChange={e => handleOrderBy(e)}>
								<option value="DESC">최신일자</option>
								<option value="ASC">오래된순</option>
							</SelectInput>
							<SelectInput className="input-select" onChange={e => handlePageSize(e)}>
								<option value="50">50개</option>
								<option value="100">100개</option>
							</SelectInput>
						</ListOption>
					</TableInfo>
					<TableStyle>
						<caption></caption>
						<thead>
							<tr>
								<th width="200">일시</th>
								<th width="200">이름</th>
								<th width="50%">ID</th>
								<th width="30%">사용 이력</th>
								{/* <th width="25%">상세 이력</th> */}
								<th width="150">상세 보기</th>
							</tr>
						</thead>
						<tbody>
							{dataList.list &&
								dataList.list.map((history, index) => (
									<Fragment key={index}>
										<tr>
											<td>{convertKTC(history.create_dt)}</td>
											<td>{history.name}</td>
											<td>{history.mail}</td>
											<td>{logOption.map(data => data.value === history.history_type && data.name)}</td>
											<td>
												<Button theme="line" text="JSON INFO" handleClick={() => handleButtonClick(history.content)} />
											</td>
										</tr>
									</Fragment>
								))}
						</tbody>
					</TableStyle>
					<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />

					<LogViewModal stateModal={stateModal} handleModal={handleModal} data={detailData} />
				</>
			)}
		</>
	);
};

export default LogView;
