import { useState, 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,
	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, ViewTableInfo} from '../../components/common';
import { convertKTC, truncateText } from '../../utils';
import { CaliumRequestRegistModal } from '../../components/UserManage';
import { CaliumCharge } from '../../apis';
import { useModal, withAuth } from '../../hooks/hook';
import { CommonSearchBar, useCommonSearch } from '../../components/ServiceManage';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import { alertTypes } from '../../assets/data/types';
import useCommonSearchOld from '../../hooks/useCommonSearchOld';

const CaliumRequest = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const { showModal, showToast } = useAlert();
	const {withLoading} = useLoading();

	const tableRef = useRef(null);
	const [selectCharge, setSelectCharge] = useState({});

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

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

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "detail":
				showModal(param, {
					type: alertTypes.info
				});
				break;
			case "chargedConfirm":
				setSelectCharge({id: param.id, count: param.count});
				showModal('CALIUM_CHARGE_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('charged')
				});
				break;
			case "charged":
				await withLoading( async () => {
					return await CaliumCharge(token, selectCharge);
				}).then(data => {
					if(data.result === "SUCCESS") {
						showToast('CHARGE_COMPLTED', {type: alertTypes.success});
					}else if(data.result === "ERROR_CALIUM_FINISH") {
						showToast('CHARGE_FINISH_FAIL', {type: alertTypes.error});
					}else{
						showToast('CHARGE_FAIL', {type: alertTypes.error});
					}
				}).catch(error => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() =>{
					setSelectCharge({});
					handleSearch(updateSearchParams);
				});
				break;
		}
	}

	return (
		<>
			<Title>칼리움 사용 수량 요청</Title>
			<FormWrapper>
				<CommonSearchBar
					config={config}
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>
			<ViewTableInfo total={dataList?.total} total_all={dataList?.total_all} handleOrderBy={handleOrderByChange} handlePageSize={handlePageSizeChange} 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?.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={searchParams.pageSize}
				totalPosts={dataList?.total_all}
				setCurrentPage={handlePageChange}
				currentPage={searchParams.currentPage}
				pageLimit={INITIAL_PAGE_LIMIT}
			/>

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

		</>
	);
};

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