import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { JSX, useEffect, useState } from 'react';
import {
  ExtensionFundAccountBalanceParams,
  ExtensionFundAccountBalanceResponse,
  ExtensionFundAccountTransferExcelParams,
  ExtensionFundAccountTransferExcelResponse,
  ExtensionFundAccountTransferListParams,
  FundAccountSearchCl,
  FundAccountStatus,
  FundAccountTransferContentItem
} from '../../model/fund-account/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import moment from 'moment';
import { useExtensionFundAccountTransferListMutation } from '../../api/fund-account/use-extension-fund-account-transfer-list-mutation';
import { ListDateGroup } from '../list-date-group';
import { AdditionalServiceCategory } from '../../model/types';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { useExtensionFundAccountTransferExcelMutation } from '../../api/fund-account/use-extension-fund-account-transfer-excel-mutation';
import { getFundAccountStatusBtnGroup } from '../../model/fund-account/constant';
import { useExtensionFundAccountBalanceMutation } from '../../api/fund-account/use-extension-fund-account-balance-mutation';
import { NumericFormat } from 'react-number-format';
import { FundAccountTransactionFilter } from '../filter/fund-account-trnasaction-filter';
import { PATHS } from '@/shared/constants/paths';
import { useStore } from '@/shared/model/store';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useTranslation } from 'react-i18next';

export const FundAccountTransferListWrap = () => {
  const { navigate } = useNavigate();
  const { t } = 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<FundAccountTransferContentItem>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [searchCl, setSearchCl] = useState<FundAccountSearchCl>(FundAccountSearchCl.ACCOUNT_NAME);
  const [searchValue, setSearchValue] = useState<string>('');
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [status, setStatus] = useState<FundAccountStatus>(FundAccountStatus.ALL);
  const [bankCode, setBankCode] = useState<string>('');

  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
  const [balance, setBalance] = useState<number>(0);

  const { mutateAsync: extensionFundAccountTransferList } = useExtensionFundAccountTransferListMutation();
  const { mutateAsync: extensionFundAccountTransferExcel } = useExtensionFundAccountTransferExcelMutation();
  const { mutateAsync: extensionFundAccountBalance } = useExtensionFundAccountBalanceMutation();
  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 listParams: ExtensionFundAccountTransferListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      bankCode: bankCode,
      fromDate: fromDate,
      toDate: toDate,
      resultStatus: status,
      page: {
				...pageParam,
				...{ sortType: sortType }
			}
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    extensionFundAccountTransferList(listParams).then((rs: any) => {
      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
      );
    });
    callBalance();
  };

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

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

  const callBalance = () => {
    let params: ExtensionFundAccountBalanceParams = {
      mid: mid
    };
    extensionFundAccountBalance(params).then((rs: ExtensionFundAccountBalanceResponse) => {
      setBalance(rs.balance);
    });
  };

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

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

  const onClickToStatus = (val: FundAccountStatus) => {
    setStatus(val);
  };

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

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    fromDate,
    toDate,
    bankCode,
    status,
    sortType
  ]);

  const onClickToNavigate = () => {
    navigate(PATHS.additionalService.fundAccount.transferRequest);
  };

  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"
              aria-label="필터"
              onClick={() => onClickToOpenFilter()}
            >
              <img
                src={IMAGE_ROOT + '/ico_setting.svg'}
                alt="검색옵션"
              />
            </button>
          </div>
          <button
            className="download-btn"
            aria-label="다운로드"
            onClick={onClickToOpenEmailBottomSheet}
          >
            <img
              src={IMAGE_ROOT + '/ico_download.svg'}
              alt={t('common.search')}
            />
          </button>
        </div>
        <div className="account-frame">
          <div className="credit-summary">
            <div className="row">
              <span className="label">{t('additionalService.fundAccount.balance')}</span>
              <span className="amount22">
                <NumericFormat
                  value={balance}
                  thousandSeparator
                  displayType="text"
                ></NumericFormat><span className="unit">{t('additionalService.fundAccount.won')}</span>
              </span>
            </div>
          </div>
        </div>
        <div className="notice-bar style-note">
          <span><span>※</span> {t('additionalService.fundAccount.transferRegistrationNotice')}</span>
        </div>
      </section>

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

      <section className="transaction-list pb-86">
        { getListDateGroup() }
      </section>
      <div ref={ setTarget }></div>
      <div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={onClickToNavigate}
        >{t('additionalService.fundAccount.transferRegistration')}</button>
      </div>
      <FundAccountTransactionFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        fromDate={fromDate}
        toDate={toDate}
        bankCode={bankCode}
        status={status}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setBankCode={setBankCode}
        setStatus={setStatus}
      ></FundAccountTransactionFilter>

      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      />
    </>
  );
};