import { useState, useEffect, 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,
	commonStatus,
	modalTypes,
	ViewTitleCountType,
	caliumStatus
} from '../../assets/data';
import { Title, FormWrapper, TableStyle, TableWrapper, PopupMessage } from '../../styles/Components';
import {
	StatusWapper,
	ChargeBtn,
	StatusLabel,
} from '../../styles/ModuleComponents';
import {Button, ExcelDownButton, Pagination, DynamicModal, ViewTableInfo, Loading} from '../../components/common';
import { convertKTC, truncateText } from '../../utils';
import { CaliumRequestRegistModal, CaliumRequestSearchBar } from '../../components/UserManage';
import { CaliumCharge, CaliumRequestView } from '../../apis';
import { withAuth } from '../../utils/hook';
import { convertEndDateToISO, convertStartDateToISO } from '../../utils/date';

const CaliumRequest = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();

	const tableRef = useRef(null);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(50);

	const [dataList, setDataList] = useState([]);
	const [detailData, setDetailData] = useState('');
	const [loading, setLoading] = useState(false);
	const [alertMsg, setAlertMsg] = useState('');
	const [selectCharge, setSelectCharge] = useState({});

	const [searchData, setSearchData] = useState({
		content: '',
		status: 'ALL',
		startDate: '',
		endDate: '',
	});
	const [orderBy, setOrderBy] = useState('DESC');
	const [modalState, setModalState] = useState({
		detailModal: 'hidden',
		registerModal: 'hidden',
		chargedCompleteModal: 'hidden',
		chargedConfirmModal: 'hidden'
	});

	useEffect(() => {
		fetchData('', 'ALL', '', '');
	}, [currentPage]);

	// 리스트 조회
	const fetchData = async (content, status, startDate, endDate, order, size) => {
		setDataList(
			await CaliumRequestView(
				token,
				content,
				status,
				startDate && convertStartDateToISO(startDate),
				endDate && convertEndDateToISO(endDate),
				order ? order : orderBy,
				size ? size : pageSize,
				currentPage,
			),
		);
	};

	// 검색 함수
	const handleSearch = (content, status, startDate, endDate) => {
		fetchData(content, status, startDate, endDate);
	};

	// 오름차순 내림차순
	const handleOrderBy = e => {
		const order = e.target.value;

		setOrderBy(order);
		fetchData(
			searchData.content,
			searchData.status,
			searchData.startDate,
			searchData.endDate,
			order,
			pageSize,
		);
	};

	const handlePageSize = e => {
		const size = e.target.value;
		setPageSize(size);
		setCurrentPage(1);

		fetchData(
			searchData.content,
			searchData.status,
			searchData.startDate,
			searchData.endDate,
			orderBy,
			size,
			1,
		);
	};

	// 상세보기 호출
	// const handleDetailModal = async (e, id) => {
	// 	await EventDetailView(token, id).then(data => {
	// 		setDetailData(data);
	// 	});
	//
	// 	e.preventDefault();
	// 	handleModalView('detail');
	// };

	const handleModalView = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'view',
		}));
	}

	const handleModalClose = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'hidden',
		}));
	}

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "detail":
				setDetailData(param);
				handleModalView('detail');
				break;
			case "chargedConfirm":
				setSelectCharge({id: param.id, count: param.count});
				handleModalView('chargedConfirm');
				break;
			case "charged":
				handleModalClose('chargedConfirm');
				setLoading(true);
				await CaliumCharge(token, selectCharge).then(data => {
					setLoading(false);
					if(data.result === "SUCCESS") {
						setAlertMsg(t('CHARGE_COMPLTED'));
						handleModalView('chargedComplete');
					}else if(data.result === "ERROR_CALIUM_FINISH") {
						setAlertMsg(t('CHARGE_FINISH_FAIL'));
						handleModalView('chargedComplete');
					}else{
						setAlertMsg(t('CHARGE_FAIL'));
						handleModalView('chargedComplete');
					}
					setSelectCharge({});
				});
				break;
			case "chargedComplete":
				handleModalClose('chargedComplete');
				await fetchData(
					searchData.content,
					searchData.status,
					searchData.startDate,
					searchData.endDate
				);
				break;
		}
	}

	return (
		<>
			<Title>칼리움 사용 수량 요청</Title>
			<FormWrapper>
				<CaliumRequestSearchBar handleSearch={handleSearch} setResultData={setSearchData} />
			</FormWrapper>
			<ViewTableInfo total={dataList.total} total_all={dataList.total_all} handleOrderBy={handleOrderBy} handlePageSize={handlePageSize} countType={ViewTitleCountType.calium}>
				<ExcelDownButton tableRef={tableRef} fileName={t('FILE_CALIUM_REQUEST')} />
				{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.eventUpdate) && (
					<Button
						theme="primary"
						text="요청 등록"
						type="button"
						handleClick={e => {
							e.preventDefault();
							handleModalView('register');
						}}
					/>
				)}
			</ViewTableInfo>
			<TableWrapper>
				<TableStyle ref={tableRef}>
					<caption></caption>
					<thead>
					<tr>
						{/*<th width="80">번호</th>*/}
						<th width="210">요청 일시</th>
						<th width="140">요청 부서</th>
						<th width="100">요청자</th>
						<th>요청 사유</th>
						<th width="80">요청수량</th>
						<th width="160">진행상태</th>
						<th width="210">최종 처리일시</th>
					</tr>
					</thead>
					<tbody>
						{dataList.list &&
							dataList.list.map(calium => (
								<Fragment key={calium.row_num}>
									<tr>
										{/*<td>{calium.row_num}</td>*/}
										<td>{convertKTC(calium.create_dt)}</td>
										<td>{calium.dept}</td>
										<td>{calium.create_by}</td>
										<td>
											<PopupMessage onClick={e => handleSubmit('detail', calium.content)}>
												{truncateText(calium.content)}
											</PopupMessage>
										</td>
										<td>{calium.count}</td>
										<StatusWapper>
											<StatusLabel $status={calium.status}>{caliumStatus.map(data => data.value === calium.status && data.name)}</StatusLabel>
											{calium.status === commonStatus.complete && userInfo.auth_list?.some(auth => auth.id === authType.eventUpdate) && calium.create_by === userInfo.name &&
												<ChargeBtn onClick={() => handleSubmit('chargedConfirm', {id: calium.id, count: calium.count})}>충전</ChargeBtn>
											}
										</StatusWapper>
										<td>{convertKTC(calium.state_time)}</td>
									</tr>
								</Fragment>
							))}
					</tbody>
				</TableStyle>
			</TableWrapper>

			<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />

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

			<CaliumRequestRegistModal registView={modalState.registerModal} setRegistView={() => handleModalClose('register')} userInfo={userInfo} />

			<DynamicModal
				modalType={modalTypes.confirmOkCancel}
				view={modalState.chargedConfirmModal}
				handleCancel={() => handleModalClose('chargedConfirm')}
				handleSubmit={() => handleSubmit('charged')}
				modalText={t('CALIUM_CHARGE_CONFIRM')}
			/>
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.chargedCompleteModal}
				modalText={alertMsg}
				handleSubmit={() => handleSubmit('chargedComplete')}
			/>
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.chargedCompleteModal}
				modalText={alertMsg}
				handleSubmit={() => handleSubmit('chargedComplete')}
			/>
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.detailModal}
				modalText={detailData}
				handleSubmit={() => handleModalClose('detail')}
			/>
			{loading && <Loading/>}
		</>
	);
};

export default withAuth(authType.caliumRequestRead)(CaliumRequest);
