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
} 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';

export interface ListWrapProps {
  startDateFromCalendar?: string;
  endDateFromCalendar?: string;
};

export const ListWrap = ({
  startDateFromCalendar,
  endDateFromCalendar
}: ListWrapProps) => {
  const { navigate } = useNavigate();
  const userMid = useStore.getState().UserStore.mid;
  
  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 [transactionIds, setTransactionIds] = useState<Array<string>>([]);
  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 = () => {
    if(periodType === SettlementPeriodType.SETTLEMENT_DATE){
      callSettlementList();
    }
    else if(periodType === SettlementPeriodType.TRANSACTION_DATE){
      callTransactionList();
    }
  };

  const callSettlementList = (option?: {
    sortType?: SortTypeKeys, 
    val?: string
  }) => {
    let listSummaryParams: SettlementsHistorySummaryParams = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
    };
    let listParams: SettlementsHistoryParams = {
      ...listSummaryParams,
      ...{
        page: pageParam
      }
    };
    if(listParams.page){
			listParams.page.sortType = (option?.sortType)? option.sortType: sortType;
    	setPageParam(listParams.page);
		}

    settlementsHistory(listParams).then((rs: SettlementsHistoryResponse) => {
      setSettlementDateListItems(rs.content);
    });
    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 = (option?: {
    sortType?: SortTypeKeys, 
    val?: string
  }) => {
    let params = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
      page: pageParam
    };
    
    let summaryParams = {
      ...params,
      ...{ 
        transactionIds: transactionIds
      }
    };
    if(params.page){
			params.page.sortType = option?.sortType || sortType;
    	setPageParam(params.page);
		}

    settlementsTransactionList(params).then((rs) => {
      setTransactionDateListItems(rs.content);
    });
    settlementsTransactionSummary(summaryParams).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);
    if(periodType === SettlementPeriodType.SETTLEMENT_DATE){
      callSettlementList({
        sortType: sort
      });
    }
    else if(periodType === SettlementPeriodType.TRANSACTION_DATE){
      callTransactionList({
        sortType: sort
      });
    }
  };
  const changePeriodType = (val: SettlementPeriodType) => {
    if(val !== periodType){
      setPeriodType(val);
      if(val === SettlementPeriodType.SETTLEMENT_DATE){
        callSettlementList();
      }
      else if(val === SettlementPeriodType.TRANSACTION_DATE){
        callTransactionList();
      }
    }
  };
  
  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(() => {
    setTransactionIds([
      'TXN_20250608_001',
      'TXN_20250608_002'
    ]);
  }, []);

  useEffect(() => {
    callList();
  }, [
    mid, periodType, 
    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="검색옵션"
                onClick={ () => onClickToOpenFilter() }
              />
            </button>
          </div>
          <button className="download-btn">
            <img 
              src={ IMAGE_ROOT + '/ico_download.svg' }
              alt="다운로드"
              onClick={ () => onClickToDownloadExcel() }
            />
          </button>
        </div>
        <div className="summary-label label">정산금액</div>
        <div className="summary-amount divTop">
          <span className="amount-text">
            <NumericFormat
              value={ settlementAmount } 
              thousandSeparator
              displayType="text"
              suffix={ '원' }
            ></NumericFormat>
          </span>
          <button
            onClick={ () => setIsOpenSummary(!isOpenSummary) }
          >
            <img 
              className={`ic20 ${(isOpenSummary)? '': 'rot-180'}`}
              src={ IMAGE_ROOT + '/ico_divTop_arrow.svg' } 
              alt="화살표"
            />
          </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>
          <div className="full-menu-keywords no-padding">
            <span 
              className={ `keyword-tag ${(periodType === SettlementPeriodType.SETTLEMENT_DATE)? 'active': ''}` }
              onClick={ () => changePeriodType(SettlementPeriodType.SETTLEMENT_DATE) }
            >가맹점 기준</span>
            <span 
              className={ `keyword-tag ${(periodType === SettlementPeriodType.TRANSACTION_DATE)? 'active': ''}` }
              onClick={ () => changePeriodType(SettlementPeriodType.TRANSACTION_DATE) }
            >거래 기준</span>
          </div>
        </div>
      </div>
      <div className="transaction-list">
      { (periodType === SettlementPeriodType.SETTLEMENT_DATE) && 
        getSettlementDateListDateGroup()
      }
    
      { (periodType === SettlementPeriodType.TRANSACTION_DATE) && 
        getTransactionDateListDateGroup()
      }
      </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>
      }
    </>
  );
};