import moment from 'moment';
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 { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { ListDateGroup } from '../list-date-group';
import { AdditionalServiceCategory } from '../../model/types';
import { ExtensionFundAccountResultExcelParams, ExtensionFundAccountResultExcelResponse, ExtensionFundAccountResultListParams, ExtensionFundAccountResultListResponse, ExtensionFundAccountResultSummaryParams, ExtensionFundAccountResultSummaryResponse, FundAccountResultContent, FundAccountResultContentItem, FundAccountResultStatus, FundAccountSearchCl, FundAccountSearchDateType, FundAccountStatus } from '../../model/fund-account/types';
import { useExtensionFundAccountResultSummaryMutation } from '../../api/fund-account/use-extension-fund-account-result-summary-mutation';
import { useExtensionFundAccountResultExcelMutation } from '../../api/fund-account/use-extension-fund-account-result-excel-mutation';
import { useExtensionFundAccountResultListMutation } from '../../api/fund-account/use-extension-fund-account-result-list-mutation';
import { PATHS } from '@/shared/constants/paths';
import { NumericFormat } from 'react-number-format';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { getFundAccountResultStatusBtnGroup, getFundAccountStatusBtnGroup } from '../../model/fund-account/constant';
import { FundAccountResultFilter } from '../filter/fund-account-result-filter';
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 FundAccountResultListWrap = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();

  let recentCursor = null;

  const userMid = useStore.getState().UserStore.mid;

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<FundAccountResultContentItem>>([]);
  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 [searchDateType, setSearchDateType] = useState<FundAccountSearchDateType>(FundAccountSearchDateType.REQUEST_DATE)
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [bankCode, setBankCode] = useState<string>('');
  const [resultStatus, setResultStatus] = useState<FundAccountResultStatus>(FundAccountResultStatus.ALL);
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const [totalRequestCount, setTotalRequestCount] = useState<number>(0);
  const [totalRequestAmount, setTotalRequestAmount] = useState<number>(0);
  const [totalSuccessCount, setTotalSuccessCount] = useState<number>(0);
  const [totalSuccessAmount, setTotalSuccessAmount] = useState<number>(0);
  const [totalFailCount, setTotalFailCount] = useState<number>(0);
  const [totalFailAmount, setTotalFailAmount] = useState<number>(0);


  const { mutateAsync: extensionFundAccountResultList } = useExtensionFundAccountResultListMutation();
  const { mutateAsync: extensionFundAccountResultExcel } = useExtensionFundAccountResultExcelMutation();
  const { mutateAsync: extensionFundAccountResultSummary } = useExtensionFundAccountResultSummaryMutation();
  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: ExtensionFundAccountResultListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      searchDateType: searchDateType,
      fromDate: fromDate,
      toDate: toDate,
      bankCode: bankCode,
      resultStatus: resultStatus,
      page: {
				...pageParam,
				...{ sortType: sortType }
			}
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

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


  const callSummary = () => {
    let params: ExtensionFundAccountResultSummaryParams = {
      mid: mid
    };

    extensionFundAccountResultSummary(params).then((rs: ExtensionFundAccountResultSummaryResponse) => {
      setTotalRequestCount(rs.totalRequestCount);
      setTotalRequestAmount(rs.totalRequestAmount);
      setTotalSuccessCount(rs.totalSuccessCount);
      setTotalSuccessAmount(rs.totalSuccessAmount);
      setTotalFailCount(rs.totalFailCount);
      setTotalFailAmount(rs.totalFailAmount);
    });
  };

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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      let params: ExtensionFundAccountResultExcelParams = {
        mid: mid,
        email: selectedEmail,
        searchDateType: searchDateType,
        fromDate: fromDate,
        toDate: toDate,
      };
      extensionFundAccountResultExcel(params).then((rs: ExtensionFundAccountResultExcelResponse) => {
        console.log('Excel Download Status:', rs);
      });
    }
    setEmailBottomSheetOn(false);
  };

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

  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };
  const onClickToStatus = (val: FundAccountResultStatus) => {
    setResultStatus(val);
  };

  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list = [];
    for (let i = 0; i < listItems.length; i++) {
      let items = listItems[i];
      if (!!items) {
        let requestDate = items?.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.FundAccountResult}
                  mid={mid}
                  key={date + '-' + i}
                  date={date}
                  items={list}
                ></ListDateGroup>
              );
            }
            date = requestDate;
            list = [];
          }
          list.push(items);
        }
      }
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.FundAccountResult}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list}
        ></ListDateGroup>
      );
    }
    return rs;
  };

  useEffect(() => {
    callSummary();
  }, []);

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    searchDateType,
    fromDate,
    toDate,
    bankCode,
    resultStatus,
    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="summary-extend">
          <ul className="summary-amount-list">
            <li className="summary-amount-item">
              <span className="label">{t('additionalService.common.request')}</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalRequestAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> {t('additionalService.fundAccount.won')} (</span>
                <span>
                  <NumericFormat
                    value={totalRequestCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">{t('additionalService.common.success')}</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalSuccessAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> {t('additionalService.fundAccount.won')} (</span>
                <span>
                  <NumericFormat
                    value={totalSuccessCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">{t('additionalService.common.fail')}</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalFailAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> {t('additionalService.fundAccount.won')} (</span>
                <span>
                  <NumericFormat
                    value={totalFailCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
          </ul>
        </div>
      </section>

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

      <section className="transaction-list">
        { 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>
      <FundAccountResultFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        searchDateType={searchDateType}
        fromDate={fromDate}
        toDate={toDate}
        bankCode={bankCode}
        resultStatus={resultStatus}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setSearchDateType={setSearchDateType}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setBankCode={setBankCode}
        setResultStatus={setResultStatus}
      ></FundAccountResultFilter>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};