import moment from 'moment';
import { AdditionalServiceCategory, ProcessResult } from '@/entities/additional-service/model/types';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } from '@/entities/common/model/types';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { JSX, useEffect, useState } from 'react';
import { useStore } from '@/shared/model/store';
import { PATHS } from '@/shared/constants/paths';
import {
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
	useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';

import { FaceAuthFilter } from '@/entities/additional-service/ui/face-auth/filter/face-auth-filter';
import { ExtensionFaceAuthExcelDownlaodPrams, ExtensionFaceAuthExcelDownlaodResponse, ExtensionFaceAuthListParams, ExtensionFaceAuthListResponse, FaceAuthListItem, FaceAuthResult, FaceAuthTransType } from '@/entities/additional-service/model/face-auth/types';
import { getAuthResultBtnGroup } from '@/entities/additional-service/model/face-auth/constant';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import { useExtensionFaceAuthListtMutation } from '@/entities/additional-service/api/face-auth/use-extension-face-auth-list-mutation';
import { useExtensionFaceAuthDownloadExcelMutation } from '@/entities/additional-service/api/face-auth/use-extension-face-auth-download-excel-mutation';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useTranslation } from 'react-i18next';

export const FaceAuthPage = () => {
	const { navigate } = useNavigate();
	const { t } = useTranslation();
	const userMid = useStore.getState().UserStore.mid;
	let recentCursor: null | string = null;

	// 권한 체크
	const { hasAccess, AccessDeniedDialog } = useExtensionAccessCheck({
		extensionCode: 'FACE_AUTH'
	});
	
	const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<FaceAuthListItem>>([]);
	const [filterOn, setFilterOn] = useState<boolean>(false);
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
	const [mid, setMid] = useState<string>(userMid);
	const [userMallId, setUserMallId] = useState<string>('');
	const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
	const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
	const [transType, setTransType] = useState<FaceAuthTransType>(FaceAuthTransType.ALL);
	const [authResult, setAuthResult] = useState<FaceAuthResult>(FaceAuthResult.ALL);
	const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

	useSetHeaderTitle(t('faceAuth.title'));
	useSetHeaderType(HeaderType.LeftArrow);
	useSetFooterMode(false);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});

	const { mutateAsync: faceAuthHistoryList } = useExtensionFaceAuthListtMutation();
	const { mutateAsync: downloadExcel } = useExtensionFaceAuthDownloadExcelMutation();
	const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
		entries.forEach((entry: IntersectionObserverEntry) => {
			if(entry.isIntersecting){
				if(onActionIntersect && !!pageParam.cursor){
					setOnActionIntersect(false);
					callList('page');
				} 
			}
		});
	};

	const { setTarget } = useIntersectionObserver({ 
		threshold: 1, 
		onIntersect 
	});

	const callList = (type?: string) => {
		let listParams: ExtensionFaceAuthListParams = {
			mid: "faceauth0m",
			userMallId: userMallId,
			fromDate: fromDate,
			toDate: toDate,
			transType: transType,
			authResult: authResult,
			page: {
				...pageParam,
				...{ sortType: sortType }
			}
		};
		if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

		faceAuthHistoryList(listParams).then((rs: ExtensionFaceAuthListResponse) => {
			if(type === 'page'){
        setListItems([
          ...listItems,
          ...rs.content
        ]);
      }
      else{
        setListItems(rs.content);
      }
			if(rs.hasNext 
				&& rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      ){
        setPageParam({
          ...pageParam,
          ...{ cursor: rs.nextCursor }
        });
      }
      else{
        setPageParam({
          ...pageParam,
          ...{ cursor: null }
        });
			}
			setOnActionIntersect(
        !!rs.hasNext 
				&& rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      );
    });
	};

	const onClickToOpenEmailBottomSheet = () => {
		setEmailBottomSheetOn(true);
	};

	const onSendRequest = (selectedEmail?: string) => {
		if(selectedEmail){
			const params: ExtensionFaceAuthExcelDownlaodPrams = {
				mid: mid,
				email: selectedEmail,
				fromDate: fromDate,
				toDate: toDate
			};
			downloadExcel(params).then((rs: ExtensionFaceAuthExcelDownlaodResponse) => {
				console.log('Excel Download Status:', rs.status);
			});
		}
		console
		setEmailBottomSheetOn(false);
	};

	const onClickToOpenFilter = () => {
		setFilterOn(!filterOn);
	};

	const onClickToSort = (sort: SortTypeKeys) => {
		setSortType(sort);
	};

	const onClickToAuthResult = (val: FaceAuthResult) => {
		setAuthResult(val);
	};

	const getListDateGroup = () => {
		let rs = [];
		let date = '';
		let list = [];
		for(let i = 0; i < listItems.length; i++){
			let item = listItems[i];
			if(!!item){
				let requestDate = item?.requestDate;
				requestDate = requestDate?.substring(0, 8);
				if(!!requestDate){
					if(i === 0){
						date = requestDate;
					}
					if(date !== requestDate){
						if(list.length > 0){
							rs.push(
								<ListDateGroup
									additionalServiceCategory={AdditionalServiceCategory.FaceAuth}
									mid={mid}
									key={date + '-' + i}
									date={date}
									items={list as any}
								></ListDateGroup>
							);
						}
						date = requestDate;
						list = [];
					}
					list.push(item);
				}
			}
		}
		if(list.length > 0){
			rs.push(
				<ListDateGroup
					additionalServiceCategory={AdditionalServiceCategory.FaceAuth}
					mid={mid}
					key={date + '-last'}
					date={date}
					items={list as any}
				></ListDateGroup>
			);
		}
		return rs;
	};

	useEffect(() => {
		callList();
	}, [
		mid, userMallId, 
		fromDate, toDate, 
		transType, authResult,
		sortType
	]);

	// if (!hasAccess) {
	//     return <AccessDeniedDialog />;
	// }
    
	return (
		<>
			<main>
				<div className="tab-content">
					<div className="tab-pane sub active">
						<section className="summary-section">
							<div className="credit-controls">
								<div>
									<input
										className="credit-period"
										type="text"
										value={moment(fromDate).format('YYYY.MM.DD') + '-' + moment(toDate).format('YYYY.MM.DD')}
										readOnly={true}
									/>
									<button
										className="filter-btn"
										aria-label={t('transaction.searchOptions')}
									>
										<img
											src={IMAGE_ROOT + '/ico_setting.svg'}
											alt={t('transaction.searchOptions')}
											onClick={() => onClickToOpenFilter()}
										/>
									</button>
								</div>
								<button
									className="download-btn"
									aria-label={t('transaction.download')}
									onClick={() => onClickToOpenEmailBottomSheet()}
								>
									<img
										src={IMAGE_ROOT + '/ico_download.svg'}
										alt={t('transaction.download')}
									/>
								</button>
							</div>
						</section>

						<div className="filter-section">
							<SortTypeBox
								sortType={sortType}
								onClickToSort={onClickToSort}
								sortOptions={[
									{ key: SortTypeKeys.LATEST, label: t('common.latest') },
									{ key: SortTypeKeys.OLDEST, label: t('common.oldest') }
								]}
							></SortTypeBox>
							<div className="excrow">
								<div className="full-menu-keywords no-padding">
									{
										getAuthResultBtnGroup(t).map((value: any, index: number) => (
											<span
												key={`key-service-code=${index}`}
												className={`keyword-tag ${(authResult === value.value) ? 'active' : ''}`}
												onClick={() => onClickToAuthResult(value.value)}
											>{value.name}</span>
										))
									}
								</div>
							</div>
						</div>
						<section className="transaction-list">
							{ getListDateGroup() }
						</section>
						<div ref={ setTarget }></div>
					</div>
				</div>
			</main>
			<FaceAuthFilter
				filterOn={filterOn}
				setFilterOn={setFilterOn}
				mid={mid}
				userMallId={userMallId}
				fromDate={fromDate}
				toDate={toDate}
				transType={transType}
				authResult={authResult}
				setMid={setMid}
				setUserMallId={setUserMallId}
				setFromDate={setFromDate}
				setToDate={setToDate}
				setTransType={setTransType}
				setAuthResult={setAuthResult}
			/>
			<EmailBottomSheet
				bottomSheetOn={emailBottomSheetOn}
				setBottomSheetOn={setEmailBottomSheetOn}
				imageSave={false}
				sendEmail={true}
				sendRequest={onSendRequest}
			></EmailBottomSheet>
		</>
	);
};