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 { 
  ExtensionFundAccountBalanceParams,
  ExtensionFundAccountBalanceResponse,
  ExtensionFundAccountTransferExcelParams, 
  ExtensionFundAccountTransferExcelResponse, 
  ExtensionFundAccountTransferListParams, 
  ExtensionFundAccountTransferListResponse, 
  FundAccountStatus, 
  FundAccountTransferContent, 
  FundAccountTransferContentItem 
} from '../../model/fund-account/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import moment from 'moment';
import { useExtensionFundAccountTransferListMutation } from '../../api/fund-account/use-extension-fund-account-transfer-list-mutation';
import { ListDateGroup } from '../list-date-group';
import { AdditionalServiceCategory } from '../../model/types';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { useExtensionFundAccountTransferExcelMutation } from '../../api/fund-account/use-extension-fund-account-transfer-excel-mutation';
import { FundAccountStatusBtnGroup } from '../../model/fund-account/constant';
import { useExtensionFundAccountBalanceMutation } from '../../api/fund-account/use-extension-fund-account-balance-mutation';
import { NumericFormat } from 'react-number-format';
import { FundAccountTransactionFilter } from '../filter/fund-account-trnasaction-filter';
import { PATHS } from '@/shared/constants/paths';

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

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<FundAccountTransferContentItem>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest001m');
  const [receiveAccountName, setReceiveAccountName] = useState<string>('');
  const [receiveAccountNo, setReceiveAccountNo] = useState<string>('');
  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 [balance, setBalance] = useState<number>(0);

  const { mutateAsync: extensionFundAccountTransferList } = useExtensionFundAccountTransferListMutation();
  const { mutateAsync: extensionFundAccountTransferExcel } = useExtensionFundAccountTransferExcelMutation();
  const { mutateAsync: extensionFundAccountBalance } = useExtensionFundAccountBalanceMutation();

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

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

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

  };

  const callDownloadExcel = () => {
    let params: ExtensionFundAccountTransferExcelParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      status: status,
    };
    extensionFundAccountTransferExcel(params).then((rs: ExtensionFundAccountTransferExcelResponse) => {

    });
  };

  const callBalance = () => {
    let params: ExtensionFundAccountBalanceParams = {
      mid: mid
    };
    extensionFundAccountBalance(params).then((rs: ExtensionFundAccountBalanceResponse) => {
      console.log(rs);
      setBalance(rs.balance);
    });
  };

  const assembleData = (content: Array<FundAccountTransferContent>) => {
    let data: any = {};
    if(content && !!content[0] && content.length > 0){
      let items: Array<FundAccountTransferContentItem> = 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.FundAccountTransfer }
            mid={ mid }
            key={ key }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  };

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

  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="account-frame">
          <div className="credit-summary">
            <div className="row">
              <span className="label">잔액</span>
              <span className="amount22">
                <NumericFormat
                  value={ balance }
                  thousandSeparator
                  displayType="text"
                ></NumericFormat><span className="unit">원</span>
              </span>
            </div>
          </div>
        </div>
        <div className="notice-bar style-note">
          <span><span>※</span> 이체 등록 후에는 별도 ‘이체요청'처리를 해야 이체가 실행됩니다. 미요청 시 이체 미진행.</span>
        </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>
      <FundAccountTransactionFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        receiveAccountName={ receiveAccountName }
        receiveAccountNo={ receiveAccountNo }
        fromDate={ fromDate }
        toDate={ toDate }
        receiveBankCode= { receiveBankCode }
        status={ status }
        setMid={ setMid }
        setReceiveAccountName={ setReceiveAccountName }
        setReceiveAccountNo={ setReceiveAccountNo }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setReceiveBankCode={ setReceiveBankCode }
        setStatus={ setStatus }
      ></FundAccountTransactionFilter>
    </>
  );
};