import moment from 'moment';
import { SortByKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { 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, FundAccountResultType, 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 { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { FundAccountStatusBtnGroup } from '../../model/fund-account/constant';
import { FundAccountResultFilter } from '../filter/fund-account-result-filter';

export const FundAccountResultListWrap = () => {
  const { navigate } = useNavigate();

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<FundAccountResultContentItem>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest00m');
  const [receiveAccountName, setReceiveAccountName] = useState<string>('');
  const [receiveAccountNo, setReceiveAccountNo] = useState<string>('');
  const [resultType, setResultType] = useState<FundAccountResultType>(FundAccountResultType.RequestDate);
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [status, setStatus] = useState<FundAccountStatus>(FundAccountStatus.ALL);
  const [receiveBankCode, setReceiveBankCode] = useState<string>('');

  const [totalCount, setTotalCount] = useState<number>(0);
  const [totalAmount, setTotalAmount] = useState<number>(0);
  const [successCount, setSuccessCount] = useState<number>(0);
  const [successAmount, setSuccessAmount] = useState<number>(0);
  const [failCount, setFailCount] = useState<number>(0);
  const [failAmount, setFailAmount] = useState<number>(0);
  const [pendingCount, setPendingCount] = useState<number>(0);
  const [pendingAmount, setPendingAmount] = useState<number>(0);

  const { mutateAsync: extensionFundAccountResultList } = useExtensionFundAccountResultListMutation();
  const { mutateAsync: extensionFundAccountResultExcel } = useExtensionFundAccountResultExcelMutation();
  const { mutateAsync: extensionFundAccountResultSummary } = useExtensionFundAccountResultSummaryMutation();

  const callList = (option?: {
      sortBy?: string, 
      val?: string
    }) => {
      
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);

    let params: ExtensionFundAccountResultListParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      status: status,
      pagination: pageParam
    };

    extensionFundAccountResultList(params).then((rs: ExtensionFundAccountResultListResponse) => {
      console.log(rs);
      setListItems(assembleData(rs.content));
    });

  };
  const callDownloadExcel = () => {
    let params: ExtensionFundAccountResultExcelParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      status: status,
    };
    extensionFundAccountResultExcel(params).then((rs: ExtensionFundAccountResultExcelResponse) => {

    });
  };
  const callSummary = () => {
    let params: ExtensionFundAccountResultSummaryParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate
    };
    extensionFundAccountResultSummary(params).then((rs: ExtensionFundAccountResultSummaryResponse) => {
      console.log(rs);
      setTotalCount(rs.totalCount);
      setTotalAmount(rs.totalAmount);
      setSuccessCount(rs.successCount);
      setSuccessAmount(rs.successAmount);
      setFailCount(rs.failCount);
      setFailAmount(rs.failAmount);
      setPendingCount(rs.pendingCount);
      setPendingAmount(rs.pendingAmount);
    });
  };

  const assembleData = (content: Array<FundAccountResultContent>) => {
    let data: any = {};
    if(content && !!content[0] && content.length > 0){
      let items: Array<FundAccountResultContentItem> = content[0].items;
      for(let i=0;i<items.length;i++){
        let groupDate = moment(items[i]?.requestDate).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(items[i]);
        }
      }
    }
    return data;
  };

  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };

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

  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callList({sortBy: sort});
  };
  const onClickToStatus = (val: FundAccountStatus) => {
    setStatus(val);
    callList({val: val});
  };

  const getListDateGroup = () => {
    let rs = [];
    if(Object.keys(listItems).length > 0){
      for (const [key, value] of Object.entries(listItems)) {
        rs.push(
          <ListDateGroup
            additionalServiceCategory={ AdditionalServiceCategory.FundAccountResult }
            mid={ mid }
            key={ key }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  };

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

  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={ () => onClickToDownloadExcel() }
          >
            <img 
              src={ IMAGE_ROOT + '/ico_download.svg' }
              alt="다운로드"
            />
          </button>
        </div>
        <div className="summary-extend">
          <ul className="summary-amount-list">
            <li className="summary-amount-item">
              <span className="label">요청</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={ pendingAmount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={ pendingCount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">성공</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={ successAmount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={ successCount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">실패</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={ failAmount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={ failCount }
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
          </ul>
        </div>
      </section>

      <section className="filter-section">
        <SortOptionsBox
          sortBy={ sortBy }
          onClickToSort={ onClickToSort }
        ></SortOptionsBox>
        <div className="excrow mr-0">
          <div className="full-menu-keywords no-padding">
            {
              FundAccountStatusBtnGroup.map((value, index) => (
                <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">
        { getListDateGroup() }
      </section>
      <div className="apply-row">
        <button 
          className="btn-50 btn-blue flex-1"
          onClick={ onClickToNavigate }
        >이체 등록</button>
      </div>
      <FundAccountResultFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        receiveAccountName={ receiveAccountName }
        receiveAccountNo={ receiveAccountNo }
        resultType={ resultType }
        fromDate={ fromDate }
        toDate={ toDate }
        receiveBankCode= { receiveBankCode }
        status={ status }
        setMid={ setMid }
        setReceiveAccountName={ setReceiveAccountName }
        setReceiveAccountNo={ setReceiveAccountNo }
        setResultType={ setResultType }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setReceiveBankCode={ setReceiveBankCode }
        setStatus={ setStatus }
      ></FundAccountResultFilter>
    </>
  );
};