import moment from 'moment';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useState, useEffect } from "react";
import { LinkPaymentHistoryFilter } from "./filter/link-payment-history-filter";
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { LinkPaymentHistoryList } from "./link-payment-history-list";
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { AdditionalServiceCategory, DetailData, ProcessResult } from "../../model/types";
import { useExtensionLinkPayHistoryListMutation } from '../../api/link-payment/use-extension-link-pay-history-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionLinkPayHistoryDownloadExcelMutation } from '../../api/link-payment/use-extension-link-pay-history-download-excel-mutation';
import { useDetailOnStore, useStore } from '@/shared/model/store';
import { ExtensionLinkPayHistoryListParams, LinkPaymentHistoryListItem, LinkPaymentPaymentMethod, LinkPaymentPaymentStatus, LinkPaymentSearchCl, LinkPaymentSendMethod, LinkPaymentSendStatus } from '../../model/link-pay/types';
import { DownloadBottomSheet, DownloadSelectedMode } from '@/entities/common/ui/download-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useTranslation } from 'react-i18next';
import { LinkPaymentHistoryDetail } from './detail/link-payment-history-detail';
import { checkGrant } from '@/shared/lib/check-grant';
import { showAlert } from '@/widgets/show-alert';
import { snackBar } from '@/shared/lib';

const getPaymentResultBtnGroup = (t: any) => [
	{ name: t('additionalService.linkPayment.all'), value: LinkPaymentPaymentStatus.ALL },
	{ name: t('additionalService.linkPayment.incompleteActive'), value: LinkPaymentPaymentStatus.ACTIVATE },
	{ name: t('additionalService.linkPayment.depositRequest'), value: LinkPaymentPaymentStatus.DEPOSIT_REQUEST },
	{ name: t('additionalService.linkPayment.paymentComplete'), value: LinkPaymentPaymentStatus.PAYMENT_COMPLETE },
	{ name: t('additionalService.linkPayment.paymentFailed'), value: LinkPaymentPaymentStatus.PAYMENT_FAIL },
	{ name: t('additionalService.linkPayment.paymentStopped'), value: LinkPaymentPaymentStatus.INACTIVE },
];

const defaultParams = {
	fromDate: moment().format('YYYYMMDD'),
	toDate: moment().format('YYYYMMDD'),
	searchCl: LinkPaymentSearchCl.PHONE,
	searchValue: '',
	paymentMethod: LinkPaymentPaymentMethod.CARD,
	paymentStatus: LinkPaymentPaymentStatus.ALL,
	sendStatus: LinkPaymentSendStatus.ALL,
	sendMethod: LinkPaymentSendMethod.ALL
}


export const LinkPaymentHistoryWrap = () => {
	const { t } = useTranslation();
	const { navigate } = useNavigate();
	const userMid = useStore.getState().UserStore.mid;

	const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
	const [filterOn, setFilterOn] = useState<boolean>(false);
	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<LinkPaymentHistoryListItem>>([]);
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);

	const [mid, setMid] = useState<string>(userMid);
	const [searchCl, setSearchCl] = useState<LinkPaymentSearchCl>(defaultParams.searchCl);
	const [searchValue, setSearchValue] = useState<string>(defaultParams.searchValue);
	const [paymentMethod, setPaymentMethod] = useState<LinkPaymentPaymentMethod>(defaultParams.paymentMethod);
	const [fromDate, setFromDate] = useState(defaultParams.fromDate);
	const [toDate, setToDate] = useState(defaultParams.toDate);
	const [paymentStatus, setPaymentStatus] = useState<LinkPaymentPaymentStatus>(defaultParams.paymentStatus);
	const [sendStatus, setSendStatus] = useState<LinkPaymentSendStatus>(defaultParams.sendStatus);
	const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(defaultParams.sendMethod);

	const [filterUsed, setFilterUsed] = useState<boolean>(false);

	const [downloadBottomSheetOn, setDownloadBottomSheetOn] = useState<boolean>(false);

	const { detailOn, setDetailOn } = useDetailOnStore();
	const [detailMid, setDetailMid] = useState<string>('');
	const [detailRequestId, setDetailRequestId] = useState<string>('');
	const [detailSubReqId, setDetailSubReqId] = useState<string>('');

	const { mutateAsync: linkPayHistoryList } = useExtensionLinkPayHistoryListMutation();
	const { mutateAsync: downloadExcel } = useExtensionLinkPayHistoryDownloadExcelMutation();

	const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
		entries.forEach((entry: IntersectionObserverEntry) => {
			if (entry.isIntersecting) {
				console.log('Element is now intersecting with the root. [' + onActionIntersect + ']');
				if (onActionIntersect && !!pageParam.cursor) {
					setOnActionIntersect(false);
					callList('page');
				}
			}
			else {
				console.log('Element is no longer intersecting with the root.');
			}
		});
	};

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

	const onClickToNavigate = () => {
		if (!checkGrant(54, 'W')) {
			showAlert(t('common.nopermission'));
			return;
		}
		navigate(PATHS.additionalService.linkPayment.request)
	};

	const callList = (type?: string) => {
		setOnActionIntersect(false);
		let listParams: ExtensionLinkPayHistoryListParams = {
			mid: mid,
			searchCl: searchCl,
			searchValue: searchValue,
			fromDate: fromDate,
			toDate: toDate,
			paymentStatus: paymentStatus,
			sendStatus: sendStatus,
			sendMethod: sendMethod,
			page: {
				...pageParam,
				...{ sortType: sortType }
			}
		};
		if (type !== 'page' && listParams.page) {
			listParams.page.cursor = null;
		}

		linkPayHistoryList(listParams).then((rs) => {
			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
			);
		}).catch((e: any) => {
			if (e.response?.data?.error?.message) {
				snackBar(e.response?.data?.error?.message);
				return;
			}
		});
	};

	const onClickToOpenDownloadBottomSheet = () => {
		if (!checkGrant(54, 'D')) {
			showAlert(t('common.nopermission'));
			return;
		}
		setDownloadBottomSheetOn(true);
	};

	const onRequestDownloadExcel = (
		selectedMode: DownloadSelectedMode,
		userEmail?: string
	) => {
		if (selectedMode === DownloadSelectedMode.EMAIL
			&& userEmail
		) {
			downloadExcel({
				mid: mid,
				email: userEmail,
				searchCl: searchCl,
				searchValue: searchValue,
				paymentMethod: paymentMethod,
				fromDate: fromDate,
				toDate: toDate,
				paymentStatus: paymentStatus,
				sendStatus: sendStatus,
				sendMethod: sendMethod,
			}).then((rs) => {
				console.log('Excel Download Status: ' + rs.status);
			}).catch((e: any) => {
				if (e.response?.data?.error?.message) {
					snackBar(e.response?.data?.error?.message);
					return;
				}
			});
		}
	};

	const onClickPaymentStatus = (val: LinkPaymentPaymentStatus) => {
		setPaymentStatus(val);
	}

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

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

	const setDetailData = (detailData: DetailData) => {
		setDetailOn(detailData.detailOn);
		if (detailData.mid) {
			setDetailMid(detailData.mid);
		}
		if (detailData.requestId) {
			setDetailRequestId(detailData.requestId);
		}
		if (detailData.subReqId) {
			setDetailSubReqId(detailData.subReqId);
		}
	};

	const checkUsedFilter = () => {
		let rs: boolean = true;
		if (fromDate === defaultParams.fromDate
			&& toDate === defaultParams.toDate
			&& searchCl === defaultParams.searchCl
			&& searchValue === defaultParams.searchValue
			&& paymentMethod === defaultParams.paymentMethod
			&& paymentStatus === defaultParams.paymentStatus
			&& sendMethod === defaultParams.sendMethod
			&& sendStatus === defaultParams.sendStatus
		) {
			rs = false;
		}
		setFilterUsed(rs);
	}

	useEffect(() => {
		callList();
		checkUsedFilter();
	}, [
		mid,
		searchCl,
		searchValue,
		paymentMethod,
		fromDate,
		toDate,
		paymentStatus,
		sendStatus,
		sendMethod,
		sortType
	]);

	return (
		<>
			<section className="summary-section pt-30">
				<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">
							<img
								src={IMAGE_ROOT + '/ico_setting.svg'}
								alt={t('common.searchOptions')}
								onClick={onClickToOpenFilter}
							/>
							{filterUsed &&
								<span className="notification-badge2"></span>
							}
						</button>
					</div>
					<button
						className="download-btn"
						aria-label={t('common.download')}
						onClick={onClickToOpenDownloadBottomSheet}
					>
						<img
							src={IMAGE_ROOT + '/ico_download.svg'}
							alt={t('common.download')}
						/>
					</button>
				</div>
			</section>

			<div className="filter-section">
				<SortTypeBox
					sortType={sortType}
					onClickToSort={onClickToSort}
				></SortTypeBox>
				<div className="excrow">
					<div className="full-menu-keywords no-padding">
						{
							getPaymentResultBtnGroup(t).map((value, index) => (
								<span
									key={`key-service-code=${index}`}
									className={`keyword-tag ${(paymentStatus === value.value) ? 'active' : ''}`}
									onClick={() => onClickPaymentStatus(value.value)}
								>{value.name}</span>
							))
						}
					</div>
				</div>
			</div>

			<LinkPaymentHistoryList
				listItems={listItems}
				additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
				mid={mid}
				setDetailData={setDetailData}
				filterUsed={filterUsed}
				onClickToOpenFilter={onClickToOpenFilter}
				onClickToOpenDownloadBottomSheet={onClickToOpenDownloadBottomSheet}
			></LinkPaymentHistoryList>
			<div ref={setTarget}></div>
			<div className="apply-row">
				<button
					className="btn-50 btn-blue flex-1"
					onClick={onClickToNavigate}
				>{t('additionalService.linkPayment.applyRequest')}</button>
			</div>
			<LinkPaymentHistoryFilter
				filterOn={filterOn}
				setFilterOn={setFilterOn}
				mid={mid}
				searchCl={searchCl}
				searchValue={searchValue}
				fromDate={fromDate}
				toDate={toDate}
				paymentStatus={paymentStatus}
				sendStatus={sendStatus}
				sendMethod={sendMethod}
				setMid={setMid}
				setSearchType={setSearchCl}
				setSearchKeyword={setSearchValue}
				setStartDate={setFromDate}
				setEndDate={setToDate}
				setPaymentStatus={setPaymentStatus}
				setSendStatus={setSendStatus}
				setSendMethod={setSendMethod}
			></LinkPaymentHistoryFilter>
			<LinkPaymentHistoryDetail
				detailOn={detailOn}
				setDetailOn={setDetailOn}
				mid={detailMid}
				requestId={detailRequestId}
				subReqId={detailSubReqId}
			></LinkPaymentHistoryDetail>
			{!!downloadBottomSheetOn &&
				<DownloadBottomSheet
					bottomSheetOn={downloadBottomSheetOn}
					setBottomSheetOn={setDownloadBottomSheetOn}
					imageMode={false}
					emailMode={true}
					sendRequest={onRequestDownloadExcel}
				></DownloadBottomSheet>
			}
		</>
	);
}