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 { SortOptionsBox } from '@/entities/common/ui/sort-options-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
} from '../model/types';
import { SortByKeys } from '@/entities/common/model/types';

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

export const ListWrap = ({
  startDateFromCalendar,
  endDateFromCalendar
}: ListWrapProps) => {
  const { navigate } = useNavigate();
  
  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [settlementDateListItems, setSettlementDateListItems] = useState<Record<string, Array<SettlementsHistoryContent>>>({});
  const [transactionDatelistItems, setTransactionDateListItems] = useState<Record<string, Array<SettlementsTransactionListContent>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest00m');
  const [periodType, setPeriodType] = useState<SettlementPeriodType>(SettlementPeriodType.SETTLEMENT_DATE);
  const [startDate, setStartDate] = useState(startDateFromCalendar? moment(startDateFromCalendar).format('YYYY-MM-DD'):  moment().format('YYYY-MM-DD'));
  const [endDate, setEndDate] = useState(endDateFromCalendar? moment(endDateFromCalendar).format('YYYY-MM-DD'):  moment().format('YYYY-MM-DD'));
  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 { 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?: {
    sortBy?: string, 
    val?: string
  }) => {
    let listSummaryParams = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
    };
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
    
    let listParams = {
      ...listSummaryParams,
      ...{pagination: pageParam}
    };
    settlementsHistory(listParams).then((rs) => {
      setSettlementDateListItems(assembleData(rs.content));
    });
    settlementsHistorySummary(listSummaryParams).then((rs) => {
      setSettlementAmount(rs.settlementAmount);
      setTransactionAmount(rs.transactionAmount);
      setPgFeeAmount(rs.pgFeeAmount);
      setHoldAmount(rs.holdAmount);
      setReleaseAmount(rs.releaseAmount);
      setOffsetAmount(rs.offsetAmount);
    });
  };
  const callTransactionList = (option?: {
    sortBy?: string, 
    val?: string
  }) => {
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
    let params = {
      mid: mid,
      periodType: periodType,
      startDate: startDate,
      endDate: endDate,
      paymentMethod: paymentMethod,
      pagination: pageParam
    };
    
    let summaryParams = {
      ...params,
      transactionIds: [
        "TXN_20250608_001",
        "TXN_20250608_002"
      ]
    };
    
    settlementsTransactionList(params).then((rs) => {
      setTransactionDateListItems(assembleData(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 assembleData = (content: Array<SettlementsHistoryContent>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let groupDate = moment(content[i]?.settlementDate).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };
  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    if(periodType === SettlementPeriodType.SETTLEMENT_DATE){
      callSettlementList({sortBy: sort});
    }
    else if(periodType === SettlementPeriodType.TRANSACTION_DATE){
      callTransactionList({sortBy: sort});
    }
  };
  const changePeriodType = (val: SettlementPeriodType) => {
    if(val !== periodType){
      setPeriodType(val);
      if(val === SettlementPeriodType.SETTLEMENT_DATE){
        callSettlementList();
      }
      else if(val === SettlementPeriodType.TRANSACTION_DATE){
        callTransactionList();
      }
    }
  };
  useEffect(() => {
    callList();
  }, [periodType]);
  
  const getSettlementDateListDateGroup = () => {
    let rs = [];
    if(Object.keys(settlementDateListItems).length > 0){
      for (const [key, value] of Object.entries(settlementDateListItems)) {
        rs.push(
          <ListDateGroup
            key={ key }
            periodType={ periodType }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  };
  const getTransactionDateListDateGroup = () => {
    let rs = [];
    if(Object.keys(transactionDatelistItems).length > 0){
      for (const [key, value] of Object.entries(transactionDatelistItems)) {
        rs.push(
          <ListDateGroup
            key={ key }
            periodType={ periodType }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToDownloadExcel = () => {
    // tid??? 확인 필요
    downloadExcel({
      // tid: tid
    }).then((rs) => {

    });
  };

  return (
    <>
      <div className="summary-section pt-30">
        <div className="credit-controls">
          <div>
            <input 
              className="credit-period" 
              type="text" 
              value={`${startDate} ~ ${endDate}`} 
              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">
        <SortOptionsBox
          sortBy={ sortBy }
          onClickToSort={ onClickToSort }
        ></SortOptionsBox>
        <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>
    </>
  );
};