import moment from 'moment';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { ListDateGroup } from './list-date-group';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { useSettlementsHistoryMutation } from '../api/use-settlements-history-mutation';
import { useSettlementsHistorySummaryMutation } from '../api/use-settlements-history-summary-mutation';
import { useSettlementsTransactionSummaryMutation } from '../api/use-settlements-transaction-summary-mutation';
import { useSettlementsTransactionListMutation } from '../api/use-settlements-transaction-list-mutation';
import { ListSummaryExtendSettlement } from './list-summary-extend-settlement';
import { ListSummaryExtendTransaction } from './list-summary-extend-transaction';
import SlideDown from 'react-slidedown';
import 'react-slidedown/lib/slidedown.css';
import { ListFilter } from './filter/list-filter';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { 
  SettlementPeriodType,
  SettlementPaymentMethod,
  SettlementsHistoryContent,
  ListDateGroupProps,
  SettlementsTransactionListContent,
  SettlementsHistoryParams,
  SettlementsHistoryResponse,
  SettlementsHistorySummaryParams,
  SettlementsHistorySummaryResponse,
  SettlementsTransactionSummaryParams
} from '../model/types';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
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 interface ListWrapProps {
  startDateFromCalendar?: string;
  endDateFromCalendar?: string;
};

export const ListWrap = ({
  startDateFromCalendar,
  endDateFromCalendar
}: ListWrapProps) => {
  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 [settlementDateListItems, setSettlementDateListItems] = useState<Array<SettlementsHistoryContent>>([]);
  const [transactionDatelistItems, setTransactionDateListItems] = useState<Array<SettlementsTransactionListContent>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [periodType, setPeriodType] = useState<SettlementPeriodType>(SettlementPeriodType.SETTLEMENT_DATE);
  const [startDate, setStartDate] = useState(startDateFromCalendar? moment(startDateFromCalendar).format('YYYYMMDD'):  moment().format('YYYYMMDD'));
  const [endDate, setEndDate] = useState(endDateFromCalendar? moment(endDateFromCalendar).format('YYYYMMDD'):  moment().format('YYYYMMDD'));
  const [paymentMethod, setPaymentMethod] = useState<SettlementPaymentMethod>(SettlementPaymentMethod.ALL);

  const [settlementAmount, setSettlementAmount] = useState<number>();
  const [transactionAmount, setTransactionAmount] = useState<number>();
  const [pgFeeAmount, setPgFeeAmount] = useState<number>();
  const [holdAmount, setHoldAmount] = useState<number>();
  const [releaseAmount, setReleaseAmount] = useState<number>();
  const [offsetAmount, setOffsetAmount] = useState<number>();
  const [paymentFeeAmount, setPaymentFeeAmount] = useState<number>();
  const [escrowFeeAmount, setEscrowFeeAmount] = useState<number>();
  const [authFeeAmount, setAuthFeeAmount] = useState<number>();
  const [vatAmount, setVatAmount] = useState<number>();
  const [preSettlementCancelOffset, setPreSettlementCancelOffset] = useState<number>();
  const [isOpenSummary, setIsOpenSummary] = useState<boolean>(false);

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

  const { mutateAsync: settlementsHistory } = useSettlementsHistoryMutation();
  const { mutateAsync: settlementsHistorySummary} = useSettlementsHistorySummaryMutation();
  const { mutateAsync: settlementsTransactionList } = useSettlementsTransactionListMutation();
  const { mutateAsync: settlementsTransactionSummary } = useSettlementsTransactionSummaryMutation();
  const { mutateAsync: downloadExcel } = useDownloadExcelMutation();

  const callList = (type?: string) => {
    setOnActionIntersect(false);
    if(periodType === SettlementPeriodType.SETTLEMENT_DATE){
      callSettlementList(type);
    }
    else if(periodType === SettlementPeriodType.TRANSACTION_DATE){
      callTransactionList(type);
    }
  };

  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 callSettlementList = (type?: string) => {
    let listSummaryParams: SettlementsHistorySummaryParams = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
    };
    let listParams: SettlementsHistoryParams = {
      ...listSummaryParams,
      ...{
        page: {
          ...pageParam,
          ...{ sortType: sortType }
        }
      }
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    settlementsHistory(listParams).then((rs: SettlementsHistoryResponse) => {
      if(type === 'page'){
        setSettlementDateListItems([
          ...settlementDateListItems,
          ...rs.content
        ]);
      }
      else{
        setSettlementDateListItems(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
      );
    });
    settlementsHistorySummary(listSummaryParams).then((rs: SettlementsHistorySummaryResponse) => {
      setSettlementAmount(rs.settlementAmount || 0);
      setTransactionAmount(rs.transactionAmount || 0);
      setPgFeeAmount(rs.pgFeeAmount || 0);
      setHoldAmount(rs.holdAmount || 0);
      setReleaseAmount(rs.releaseAmount || 0);
      setOffsetAmount(rs.offsetAmount || 0);
    });
  };
  const callTransactionList = (type?: string) => {
    let listSummaryParams: SettlementsTransactionSummaryParams = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
      page: pageParam
    };
    let listParams = {
      ...listSummaryParams,
      ...{
        page: {
          ...pageParam,
          ...{ sortType: sortType }
        }
      }
    };
    
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }
    settlementsTransactionList(listParams).then((rs) => {
      if(type === 'page'){
        setTransactionDateListItems([
          ...transactionDatelistItems,
          ...rs.content
        ]);
      }
      else{
        setTransactionDateListItems(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
      );
    });
    settlementsTransactionSummary(listSummaryParams).then((rs) => {
      setSettlementAmount(rs.settlementAmount);
      setTransactionAmount(rs.transactionAmount);
      setPaymentFeeAmount(rs.paymentFeeAmount);
      setEscrowFeeAmount(rs.escrowFeeAmount);
      setAuthFeeAmount(rs.authFeeAmount);
      setVatAmount(rs.vatAmount);
      setPreSettlementCancelOffset(rs.preSettlementCancelOffset);
    });
  };
  
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };
  const changePeriodType = (val: SettlementPeriodType) => {
    if(val !== periodType){
      setPeriodType(val);
    }
  };
  
  const getSettlementDateListDateGroup = () => {
    let rs = [];
    let date = '';
    let list: Array<SettlementsHistoryContent> = [];
    
    for(let i=0;i<settlementDateListItems.length;i++){
      let listItem = settlementDateListItems[i];
      if(!!listItem){
        let settlementDateTime = listItem?.settlementDate;
        let settlementDate = settlementDateTime?.substr(0, 8);
        
        if(settlementDateListItems[i] && settlementDate){
          if(i === 0){
            date = settlementDate;
          }
          if(date !== settlementDate){
            if(list.length > 0){
              rs.push(
                <ListDateGroup
                  key={ date + '-' + i }
                  periodType={ periodType }
                  date={ date }
                  items={ list }
                ></ListDateGroup>
              );
            }
            date = settlementDate;
            list = [];
          }
          list.push(listItem);
        }
      }
    }
    if(list.length > 0){
      rs.push(
        <ListDateGroup
          key={ date + '-last' }
          periodType={ periodType }
          date={ date }
          items={ list }
        ></ListDateGroup>
      );
    }
   
    return rs;
  };
  const getTransactionDateListDateGroup = () => {
    let rs = [];
    let date = '';
    let list: Array<SettlementsTransactionListContent> = [];
    
    for(let i=0;i<transactionDatelistItems.length;i++){
      let listItem = transactionDatelistItems[i];
      if(!!listItem){
        let settlementDateTime = listItem.settlementDate;
        let settlementDate = settlementDateTime?.substr(0, 8);
        
        if(settlementDate){
          if(i === 0){
            date = settlementDate;
          }
          if(date !== settlementDate){
            if(list.length > 0){
              rs.push(
                <ListDateGroup
                  key={ date + '-' + i }
                  periodType={ periodType }
                  date={ date }
                  items={ list }
                ></ListDateGroup>
              );
            }
            date = settlementDate;
            list = [];
          }
          list.push(listItem);
        }
      }
      
    }
    if(list.length > 0){
      rs.push(
        <ListDateGroup
          key={ date + '-last' }
          periodType={ periodType }
          date={ date }
          items={ list }
        ></ListDateGroup>
      );
    }
    
    return rs;
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToDownloadExcel = () => {
    setEmailBottomSheetOn(true);
  };

  const onRequestDownloadExcel = (userEmail?: string) => {
    // tid??? 확인 필요
    /*
    downloadExcel({
      // tid: tid
    }).then((rs) => {

    });
    */
  };
    
  useEffect(() => {
    callList();
  }, [
    mid, periodType, sortType,
    startDate, endDate,
    paymentMethod
  ]);  

  return (
    <>
      <div className="summary-section pt-30">
        <div className="credit-controls">
          <div>
            <input 
              className="credit-period" 
              type="text" 
              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="summary-label label">{t('settlement.settlementAmount')}</div>
        <div className="summary-amount divTop">
          <span className="amount-text">
            {t('home.money', { value: new Intl.NumberFormat('en-US').format(settlementAmount || 0) })}
          </span>
          <button
            onClick={ () => setIsOpenSummary(!isOpenSummary) }
          >
            <img
              className={`ic20 ${(isOpenSummary)? '': 'rot-180'}`}
              src={ IMAGE_ROOT + '/ico_divTop_arrow.svg' }
              alt={t('settlement.arrow')}
            />
          </button>
        </div>
        
        { (periodType === SettlementPeriodType.SETTLEMENT_DATE) && 
          <SlideDown className={'my-dropdown-slidedown'}>
          { isOpenSummary &&
            <ListSummaryExtendSettlement
              settlementAmount={ settlementAmount }
              transactionAmount={ transactionAmount }
              pgFeeAmount={ pgFeeAmount }
              holdAmount={ holdAmount }
              releaseAmount={ releaseAmount }
              offsetAmount={ offsetAmount }
            ></ListSummaryExtendSettlement>
          }
          </SlideDown>
        }
        { (periodType === SettlementPeriodType.TRANSACTION_DATE) && 
          <SlideDown className={'my-dropdown-slidedown'}>
          { isOpenSummary &&
            <ListSummaryExtendTransaction
              settlementAmount={ settlementAmount }
              transactionAmount={ transactionAmount }
              paymentFeeAmount={ paymentFeeAmount }
              escrowFeeAmount={ escrowFeeAmount }
              authFeeAmount={ authFeeAmount }
              vatAmount={ vatAmount }
              preSettlementCancelOffset={ preSettlementCancelOffset }
            ></ListSummaryExtendTransaction>
          }
          </SlideDown>
        }
      </div>

      <div className="filter-section">
        <SortTypeBox
          sortType={ sortType }
          onClickToSort={ onClickToSort }
        ></SortTypeBox>
        <div className="excrow">
          <div className="full-menu-keywords no-padding">
            <span
              className={ `keyword-tag ${(periodType === SettlementPeriodType.SETTLEMENT_DATE)? 'active': ''}` }
              onClick={ () => changePeriodType(SettlementPeriodType.SETTLEMENT_DATE) }
            >{t('settlement.merchantBasis')}</span>
            <span
              className={ `keyword-tag ${(periodType === SettlementPeriodType.TRANSACTION_DATE)? 'active': ''}` }
              onClick={ () => changePeriodType(SettlementPeriodType.TRANSACTION_DATE) }
            >{t('settlement.transactionBasis')}</span>
          </div>
        </div>
      </div>
      <div className="transaction-list">
      { (periodType === SettlementPeriodType.SETTLEMENT_DATE) && 
        getSettlementDateListDateGroup()
      }
    
      { (periodType === SettlementPeriodType.TRANSACTION_DATE) && 
        getTransactionDateListDateGroup()
      }
      </div>
      <div ref={ setTarget }></div>
      <ListFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        periodType={ periodType }
        startDate={ startDate }
        endDate={ endDate }
        paymentMethod={ paymentMethod }
        setMid={ setMid }
        setPeriodType={ setPeriodType }
        setStartDate={ setStartDate }
        setEndDate={ setEndDate }
        setPaymentMethod={ setPaymentMethod }
      ></ListFilter>
      { !!emailBottomSheetOn &&
        <EmailBottomSheet
          bottomSheetOn={ emailBottomSheetOn }
          setBottomSheetOn={ setEmailBottomSheetOn }
          imageSave={ false }
          sendEmail={ true }
          sendRequest={ onRequestDownloadExcel }
        ></EmailBottomSheet>
      }
    </>
  );
};