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

import {
	BuildingView,
	LandAuctionDelete,
	LandAuctionDetailView, LandView, LogHistory,
} from '../../apis';

import { authList } from '../../store/authList';
import {
	authType,
	modalTypes,
	landAuctionStatusType,
	landAuctionStatus,
	landSize,
	caliumStatus, commonStatus,
} from '../../assets/data';
import { Title, FormWrapper, TableStyle, TableWrapper} from '../../styles/Components';
import {
	CheckBox,
	Button,
	DynamicModal,
	Pagination,
	ViewTableInfo, ExcelDownButton,
} from '../../components/common';
import { convertKTC, timeDiffMinute } from '../../utils';
import { LandAuctionModal, LandAuctionSearchBar } from '../../components/ServiceManage';
import { INITIAL_PAGE_SIZE, INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { useDataFetch, useModal, useTable, withAuth } from '../../hooks/hook';
import { useLandAuctionSearch } from '../../components/searchBar/LandAuctionSearchBar';
import { StatusWapper, ChargeBtn, StatusLabel } from '../../styles/ModuleComponents';
import { alertTypes } from '../../assets/data/types';
import { useAlert } from '../../context/AlertProvider';
import LogDetailModal from '../../components/common/modal/LogDetailModal';
import { historyTables } from '../../assets/data/data';
import { AnimatedPageWrapper } from '../../components/common/Layout';

const LandAuction = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const tableRef = useRef(null);
	const { showToast, showModal } = useAlert();

	const [detailData, setDetailData] = useState({});
	const [historyData, setHistoryData] = useState({});

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		history: 'hidden'
	});
	const [alertMsg, setAlertMsg] = useState('');
	const [modalType, setModalType] = useState('regist');

	const {
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams
	} = useLandAuctionSearch(token, INITIAL_PAGE_SIZE);

	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.auction_list || [], {mode: 'single'});

	const {
		data: landData
	} = useDataFetch(() => LandView(token), [token]);

	const {
		data: buildingData
	} = useDataFetch(() => BuildingView(token), [token]);

	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "history":
				const params = {};
				params.db_type = "MYSQL"
				params.sql_id = param.id;
				params.table_name = historyTables.landAuction

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					handleModalView('history');
				});
				break;
			case "regist":
				setModalType('regist');
				handleModalView('detail');
				break;
			case "detail":
				await LandAuctionDetailView(token, param).then(data => {
					setDetailData(data.auction_detail);
					setModalType('modify');
					handleModalView('detail');
				});
				break;
			case "delete":
				const date_check = selectedRows.every(row => {
					const timeDiff = timeDiffMinute(convertKTC(row.auction_start_dt), (new Date));
					return timeDiff < 3;
				});
				if(date_check){
					showToast('LAND_AUCTION_DELETE_DATE_WARNING', {type: alertTypes.warning});
					return;
				}
				if(selectedRows[0].status === landAuctionStatusType.auction_start || selectedRows[0].status === landAuctionStatusType.stl_end){
					showToast('LAND_AUCTION_DELETE_STATUS_WARNING', {type: alertTypes.warning});
					return;
				}
				showModal('LAND_AUCTION_SELECT_DELETE', {
					type: alertTypes.confirm,
					onConfirm: () => handleModalSubmit('deleteConfirm')
				});
				break;
			case "deleteConfirm":
				let list = [];
				let isChecked = false;

				selectedRows.map(data => {
					// const row = dataList.list.find(row => row.id === Number(data.id));
					// if(row.status !== commonStatus.wait) isChecked = true;
					list.push({
						id: data.id,
					});
				});

				if(isChecked) {
					showToast('LAND_AUCTION_WARNING_DELETE', {type: alertTypes.warning});
					return;
				}

				await LandAuctionDelete(token, list).then(data => {
					if(data.result === "SUCCESS") {
						showToast('DEL_COMPLETE', {type: alertTypes.success});
					}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;
		}
	}

	return (
		<AnimatedPageWrapper>
			<Title>랜드 경매 관리</Title>
			<FormWrapper>
				<LandAuctionSearchBar
					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}>
				<ExcelDownButton tableRef={tableRef} fileName={t('FILE_LAND_AUCTION')} />
				{userInfo.auth_list?.some(auth => auth.id === authType.landAuctionDelete) && (
					<Button theme={selectedRows.length === 0 ? 'disable' : 'line'} text="선택 취소" handleClick={() => handleModalSubmit('delete')} />
				)}
				{userInfo.auth_list?.some(auth => auth.id === authType.landAuctionUpdate) && (
					<Button
						theme="primary"
						text="경매 등록"
						type="button"
						handleClick={e => handleModalSubmit('regist')}
					/>
				)}
			</ViewTableInfo>
			<TableWrapper>
				<TableStyle ref={tableRef}>
					<caption></caption>
					<thead>
					<tr>
						<th width="40"></th>
						{/*<th width="80">번호</th>*/}
						<th width="90">경매 상태</th>
						<th width="80">랜드 크기</th>
						<th width="200">랜드 이름</th>
						<th width="90">인스턴스 수</th>
						{/*<th width="100">경매 재화</th>*/}
						<th width="90">경매 시작가</th>
						<th width="200">예약 시작일</th>
						<th width="200">예약 종료일</th>
						<th width="200">경매 시작일</th>
						<th width="200">경매 종료일</th>
						<th width="200">낙찰 정산일</th>
						<th width="90">낙찰 정산가</th>
						<th width="100">낙찰자</th>
						<th width="100">확인 / 수정</th>
						<th width="150">히스토리</th>
					</tr>
					</thead>
					<tbody>
					{dataList?.auction_list?.map(auction => (
								<tr key={auction.row_num}>
									<td>
										<CheckBox name={'select'} id={auction.id}
												  setData={(e) => handleSelectRow(e, auction)}
												  checked={isRowSelected(auction.id)} />
									</td>
									{/*<td>{event.row_num}</td>*/}
									<StatusWapper>
										<StatusLabel $status={auction.status}>
											{landAuctionStatus.find(data => data.value === auction.status).name}
										</StatusLabel>
									</StatusWapper>
									{/*<td>{landAuctionStatus.find(data => data.value === auction.status)?.name}</td>*/}
									<td>{auction.land_size}</td>
									<td>{auction.land_name}</td>
									<td>{auction.land_socket}</td>
									{/*<td>{auction.currency_type}</td>*/}
									<td>{auction.start_price}</td>
									<td>{convertKTC(auction.resv_start_dt)}</td>
									<td>{convertKTC(auction.resv_end_dt)}</td>
									<td>{convertKTC(auction.auction_start_dt)}</td>
									<td>{convertKTC(auction.auction_end_dt)}</td>
									<td>{convertKTC(auction.close_end_dt)}</td>
									<td>{auction.close_price}</td>
									<td>{auction.bidder_nickname}</td>
									<td>
										<Button theme="line" text="상세보기"
												handleClick={e => handleModalSubmit('detail', auction.id)} />
									</td>
									<td><Button theme="line" text="히스토리"
												handleClick={e => handleModalSubmit('history', auction)} /></td>
								</tr>
						))}
					</tbody>
				</TableStyle>
			</TableWrapper>

			<Pagination postsPerPage={searchParams.pageSize} totalPosts={dataList?.total_all} setCurrentPage={handlePageChange} currentPage={searchParams.currentPage} pageLimit={INITIAL_PAGE_LIMIT} />

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

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

		</AnimatedPageWrapper>
	)
};

export default withAuth(authType.landAuctionRead)(LandAuction);
