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, 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 { useStore } from '@/shared/model/store';
import { ExtensionLinkPayHistoryListParams, LinkPaymentHistoryListItem, LinkPaymentPaymentMethod, LinkPaymentPaymentStatus, LinkPaymentSearchCl, LinkPaymentSendMethod, LinkPaymentSendStatus } from '../../model/link-pay/types';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useTranslation } from 'react-i18next';

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 },
];

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>(LinkPaymentSearchCl.PHONE);
	const [searchValue, setSearchValue] = useState<string>('');
	const [paymentMethod, setPaymentMethod] = useState<LinkPaymentPaymentMethod>(LinkPaymentPaymentMethod.CARD);
	const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
	const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
	const [paymentStatus, setPaymentStatus] = useState<LinkPaymentPaymentStatus>(LinkPaymentPaymentStatus.ALL);
	const [sendStatus, setSendStatus] = useState<LinkPaymentSendStatus>(LinkPaymentSendStatus.ALL);
	const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(LinkPaymentSendMethod.ALL);
	const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

	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 = () => {
		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
      );
		});
	};

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

	const onSendRequest = (selectedEmail?: string) => {
		if (selectedEmail) {
			downloadExcel({
				mid: mid,
				email: selectedEmail,
				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);
			});
		}
		setEmailBottomSheetOn(false);
	};

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

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

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

	useEffect(() => {
		callList();
	}, [
		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()}
							/>
						</button>
					</div>
					<button
						className="download-btn"
						aria-label={t('common.download')}
						onClick={() => onClickToOpenEmailBottomSheet()}
					>
						<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}
			></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>
			<EmailBottomSheet
				bottomSheetOn={emailBottomSheetOn}
				setBottomSheetOn={setEmailBottomSheetOn}
				imageSave={false}
				sendEmail={true}
				sendRequest={onSendRequest}
			></EmailBottomSheet>
		</>
	);
}