import moment from 'moment';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NumericFormat } from 'react-number-format';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { CashReceiptList } from '@/entities/transaction/ui/cash-receipt-list';
import { 
	TransactionCategory, 
	CashReceiptPurposeType, 
	CashReceiptProcessResult, 
	ListItemProps, 
	CashReceiptListParams, 
	CashReceiptTransactionType, 
	CashReceiptSearchNumberType, 
	CashReceiptSummaryParams, 
	CashReceiptListResponse, 
	CashReceiptSummaryResponse 
} from '@/entities/transaction/model/types';
import { useCashReceiptListMutation } from '@/entities/transaction/api/use-cash-receipt-list-mutation';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { CashReceiptFilter } from '@/entities/transaction/ui/filter/cash-receipt-filter';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { SortTypeKeys, HeaderType, DefaultRequestPagination } from '@/entities/common/model/types';
import {
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { CashReceiptTransactionTypeBtnGroup } from '@/entities/transaction/model/contant';
import { useStore } from '@/shared/model/store';
import { useCashReceiptSummaryMutation } from '@/entities/transaction/api/use-cash-receipt-summary-mutation';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';

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

	const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<ListItemProps>>([]);
	const [filterOn, setFilterOn] = useState<boolean>(false);
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
	const [mid, setMid] = useState<string>(userMid);
	const [startDate, setStartDate] = useState(moment().subtract(1, 'month').format('YYYYMMDD'));
	const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
	const [purposeType, setPurposeType] = useState<CashReceiptPurposeType>(CashReceiptPurposeType.ALL);
	const [transactionType, setTransactionType] = useState<CashReceiptTransactionType>(CashReceiptTransactionType.ALL);
	const [processResult, setProcessResult] = useState<CashReceiptProcessResult>(CashReceiptProcessResult.ALL);
	const [searchNumberType, setSearchNumberType] = useState<CashReceiptSearchNumberType>(CashReceiptSearchNumberType.APPROVAL_NUMBER);
	const [searchNumber, setSearchNumber] = useState<string>('');
	const [approvalCount, setApprovalCount] = useState<number>(0);
	const [approvalAmount, setApprovalAmount] = useState<number>(0);
	const [cancelCount, setCancelCount] = useState<number>(0);
	const [cancelAmount, setCancelAmount] = useState<number>(0);
	const [totalCount, setTotalCount] = useState<number>(0);

	const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

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

	const { mutateAsync: cashReceiptList } = useCashReceiptListMutation();
	const { mutateAsync: cashReceiptSummary } = useCashReceiptSummaryMutation();
	const { mutateAsync: downloadExcel } = useDownloadExcelMutation();
	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) => {
		setOnActionIntersect(false);
		let listSummaryParams: CashReceiptSummaryParams = {
			mid: mid,
			startDate: startDate,
			endDate: endDate,
			purposeType: purposeType,
			transactionType: transactionType,
			processResult: processResult,
			searchNumberType: searchNumberType,
			searchNumber: searchNumber,
			page: pageParam
		};
		let listParams: CashReceiptListParams = {
			...listSummaryParams,
			page: {
				...pageParam,
				...{ sortType: sortType }
			}
		};
		if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }
		
		cashReceiptList(listParams).then((rs: CashReceiptListResponse) => {
			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
      );
		});
		cashReceiptSummary(listSummaryParams).then((rs: CashReceiptSummaryResponse) => {
			setApprovalCount(rs.approvalCount);
			setApprovalAmount(rs.approvalAmount);
			setCancelCount(rs.cancelCount);
			setCancelAmount(rs.cancelAmount);
			setTotalCount(rs.totalCount);
		});

	}

	const onRequestDownloadExcel = (userEmail?: string) => {
    setEmailBottomSheetOn(true);
  };

	const onClickToOpenFilter = () => {
		setFilterOn(!filterOn);
	};
	const onClickToDownloadExcel = () => {
		// tid??? 확인 필요
		downloadExcel({
			// tid: tid
		}).then((rs) => {

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

	const onClickToTransactionType = (val: CashReceiptTransactionType) => {
		setTransactionType(val);
	};

	useEffect(() => {
    callList();
  }, [
    mid, startDate, endDate, sortType,
    purposeType, transactionType, processResult,
    searchNumberType, searchNumber
  ]);

	return (
		<>
			<main>
				<div className="tab-content">
					<div className="tab-pane sub active">
						<div className="summary-section">
							<div className="credit-controls">
								<div>
									<input
										type="text"
										className="credit-period"
										value={ moment(startDate).format('YYYY.MM.DD') + '-' + moment(endDate).format('YYYY.MM.DD') }
										readOnly={ true }
									/>
									<button className="filter-btn">
										<img
											src={ IMAGE_ROOT + '/ico_setting.svg' }
											alt={ t('transaction.searchOptions') }
											onClick={ () => onClickToOpenFilter() }
										/>
									</button>
								</div>
								<button className="download-btn">
									<img
										src={IMAGE_ROOT + '/ico_download.svg'}
										alt={ t('transaction.download') }
										onClick={() => onClickToDownloadExcel()}
									/>
								</button>
							</div>
							<div className="credit-summary">
								<div className="row">
									<span className="label">{ t('cashReceipt.approval') }</span>
									<strong className="amount22">
										{t('home.money', { value: new Intl.NumberFormat('en-US').format(approvalAmount || 0) })}
									</strong>
									<span className="count">
										<NumericFormat
											value={ approvalCount }
											thousandSeparator
											displayType="text"
											prefix='('
											suffix='건)'
										></NumericFormat>
									</span>
								</div>
								<div className="row">
									<span className="label">{ t('common.cancel') }</span>
									<strong className="amount19">
										{t('home.money', { value: new Intl.NumberFormat('en-US').format(cancelAmount || 0) })}
									</strong>
									<span className="count">
										<NumericFormat
											value={ cancelCount }
											thousandSeparator
											displayType="text"
											prefix='('
											suffix='건)'
										></NumericFormat>
									</span>
								</div>
							</div>
						</div>

						<div className="filter-section">
							<SortTypeBox
								sortType={ sortType }
								onClickToSort={ onClickToSort }
							></SortTypeBox>
							<div>
								<div className="full-menu-keywords no-padding">
								{
									CashReceiptTransactionTypeBtnGroup.map((value, index) => (
										<span
											key={`key-service-code=${index}`}
											className={`keyword-tag ${(transactionType === value.value) ? 'active' : ''}`}
											onClick={() => onClickToTransactionType(value.value)}
										>{value.name}</span>
									))
								}
								</div>
							</div>
						</div>
						<CashReceiptList
							listItems={ listItems }
							transactionCategory={ TransactionCategory.CashReceipt }
						></CashReceiptList>
						<div ref={ setTarget }></div>
					</div>
				</div>
			</main>
			<CashReceiptFilter
				filterOn={ filterOn }
				setFilterOn={ setFilterOn }
				mid={ mid }
				startDate={ startDate }
				endDate={ endDate }
				purposeType={ purposeType }
				transactionType={ transactionType }
				processResult={ processResult }
				searchNumberType={ searchNumberType }
				searchNumber={ searchNumber }
				setMid={ setMid }
				setStartDate={ setStartDate }
				setEndDate={ setEndDate }
				setPurposeType={ setPurposeType }
				setTransactionType={ setTransactionType }
				setProcessResult={ setProcessResult }
				setSearchNumberType={ setSearchNumberType }
				setSearchNumber={ setSearchNumber }
			></CashReceiptFilter>
			{ !!emailBottomSheetOn &&
				<EmailBottomSheet
					bottomSheetOn={ emailBottomSheetOn }
					setBottomSheetOn={ setEmailBottomSheetOn }
					imageSave={ false }
					sendEmail={ true }
					sendRequest={ onRequestDownloadExcel }
				></EmailBottomSheet>
			}
		</>
	);
};