import { styled } from 'styled-components';
import { Link } from 'react-router-dom';
import React, { Fragment, useRef, useState } from 'react';

import {
	Title,
	TableStyle,
	BtnWrapper,
	ButtonClose,
	ModalText,
	FormWrapper,
	TableWrapper,
} from '../../styles/Components';

import Button from '../../components/common/button/Button';

import { useNavigate } from 'react-router-dom';
import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { useDataFetch, useModal, useTable, withAuth } from '../../utils/hook';
import {
	authType,
	landAuctionStatus,
	landSize,
	modalTypes,
	opLandCategoryType,
	opLandOwnedType,
} from '../../assets/data';
import { useLandAuctionSearch } from '../../components/ServiceManage/searchBar/LandAuctionSearchBar';
import { INITIAL_PAGE_LIMIT, INITIAL_PAGE_SIZE, TYPE_MODIFY } from '../../assets/data/adminConstants';
import { useTranslation } from 'react-i18next';
import { CheckBox, DynamicModal, ExcelDownButton, Pagination, ViewTableInfo } from '../../components/common';
import { LandAuctionSearchBar } from '../../components/ServiceManage';
import LandInfoSearchBar, { useLandInfoSearch } from '../../components/ServiceManage/searchBar/LandInfoSearchBar';
import { convertKTCDate } from '../../utils';
import Loading from '../../components/common/Loading';
import { TableSkeleton } from '../../components/Skeleton/TableSkeleton';
import OwnerChangeModal from '../../components/ServiceManage/modal/OwnerChangeModal';
import { StatusLabel, StatusWapper } from '../../styles/ModuleComponents';
import { opLandInfoStatusType } from '../../assets/data/options';

const LandInfoView = () => {
	const token = sessionStorage.getItem('token');
	const navigate = useNavigate();
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const tableRef = useRef(null);

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

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

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

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

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

	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "regist":
				setModalType('regist');
				const selectRow = selectedRows[0];
				if(!selectRow.owned) {
					setAlertMsg(t('LAND_OWNED_CHANGES_WARNING'))
					return;
				}
				const owner_changes = selectRow.owner_changes;
				if(owner_changes.length > 0){
					setModalType(TYPE_MODIFY);
				}
				setDetailData(selectRow);
				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){
			// 		setAlertMsg(t('LAND_AUCTION_DELETE_DATE_WARNING'));
			// 		return;
			// 	}
			// 	if(selectedRows[0].status === landAuctionStatusType.auction_start || selectedRows[0].status === landAuctionStatusType.stl_end){
			// 		setAlertMsg(t('LAND_AUCTION_DELETE_STATUS_WARNING'));
			// 		return;
			// 	}
			// 	handleModalView('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) {
			// 		setAlertMsg(t('LAND_AUCTION_WARNING_DELETE'))
			// 		handleModalClose('deleteConfirm');
			// 		return;
			// 	}
			//
			// 	await LandAuctionDelete(token, list).then(data => {
			// 		handleModalClose('deleteConfirm');
			// 		if(data.result === "SUCCESS") {
			// 			handleModalView('deleteComplete');
			// 		}else{
			// 			setAlertMsg(t('DELETE_FAIL'));
			// 		}
			// 	}).catch(reason => {
			// 		setAlertMsg(t('API_FAIL'));
			// 	});
			//
			// 	break;
			// case "deleteComplete":
			// 	handleModalClose('deleteComplete');
			// 	// fetchData(option);
			// 	window.location.reload();
			// 	break;
			case "warning":
				setAlertMsg('')
				break;
		}
	}

	return (
		<>
			<Title>랜드 정보 조회</Title>
			<FormWrapper>
				<LandInfoSearchBar
					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.landUpdate) && (
					<Button
						theme={selectedRows.length === 0 ? 'disable' : 'line'}
						text="소유권 변경"
						type="button"
						handleClick={e => handleModalSubmit('regist')}
					/>
				)}
			</ViewTableInfo>
			{loading ? <TableSkeleton width='100%' count={15} /> :
			<TableWrapper>
				<TableStyle ref={tableRef}>
					<thead>
					<tr>
						<th width="40"></th>
						<th width="150">랜드 ID</th>
						<th>랜드 이름</th>
						<th>랜드 상태</th>
						<th>카테고리</th>
						<th>랜드 크기</th>
						<th>인스턴스 수</th>
						<th>유저 소유 여부</th>
						<th>보유자</th>
						<th>보유시작일</th>
						<th>낙찰 가격</th>
					</tr>
					</thead>
					<tbody>
						{dataList?.land_info_list?.map((data, index) => (
							<Fragment key={index}>
								<tr>
									<td>
										<CheckBox name={'select'} id={data.id}
												  setData={(e) => handleSelectRow(e, data)}
												  checked={isRowSelected(data.id)} />
									</td>
									<td>{data.land_id}</td>
									<td>{data.land_name}</td>
									<td>{opLandInfoStatusType.find(option => option.value === data.status)?.name}</td>
									<td>{opLandCategoryType.find(option => option.value === data.category)?.name}</td>
									<td>{landSize.find(option => option.value === data.land_size)?.name}</td>
									<td>{data.socket}</td>
									<td>{opLandOwnedType.find(option => option.value === data.owned)?.name}</td>
									<td>{data.owner_user_nickname}</td>
									{/*<td>{convertKTCDate(data.owner_user_create_date)}</td>*/}
									<td>{data.owner_user_create_date}</td>
									<td>{Number(data.owner_price) > 0 ? data.owner_price : ''}</td>
								</tr>
							</Fragment>
						))}
					</tbody>
				</TableStyle>
			</TableWrapper>
			}

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

			<OwnerChangeModal modalType={modalType} detailView={modalState.detailModal} handleDetailView={() => {handleModalClose('detail');handleSearch()}} content={detailData} setDetailData={setDetailData} />

			<DynamicModal
				modalType={modalTypes.completed}
				view={alertMsg ? 'view' : 'hidden'}
				modalText={alertMsg}
				handleSubmit={() => handleModalSubmit('warning')}
			/>
		</>
	);
};

export default withAuth(authType.landRead)(LandInfoView);

// const TableWrapper = styled.div`
// 	overflow: auto;
// 	border-top: 1px solid #000;
//     z-index: 1;
// 	&::-webkit-scrollbar {
// 		height: 4px;
// 	}
// 	&::-webkit-scrollbar-thumb {
// 		background: #666666;
// 	}
// 	&::-webkit-scrollbar-track {
// 		background: #d9d9d9;
// 	}
// 	thead {
// 		th {
// 			position: sticky;
// 			top: 0;
// 			z-index: 10;
// 		}
// 	}
// 	${TableStyle} {
// 		min-width: 1000px;
// 		th {
// 			position: sticky;
// 			top: 0;
// 		}
// 	}
// `;

const LandLink = styled(Link)`
	color: #61a2d0;
	text-decoration: underline;
`;
