import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType, SortByKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useExtensionPayoutListMutation } from '@/entities/additional-service/api/payout/use-extension-payout-list-mutation';
import {
  ExtensionPayoutExcelParams,
  ExtensionPayoutExcelResponse,
  ExtensionPayoutListParams,
  ExtensionPayoutListResponse,
  PayoutContent,
  PayoutDisbursementStatus,
  PayoutSearchCl
} from '@/entities/additional-service/model/payout/types';
import { useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import moment from 'moment';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { useExtensionPayoutExcelMutation } from '@/entities/additional-service/api/payout/use-extension-payout-excel-mutation';
import { PayoutFilter } from '@/entities/additional-service/ui/filter/payout-filter';
import { PayoutDisbursementStatusBtnGroup } from '@/entities/additional-service/model/payout/constant';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';

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

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<PayoutContent>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest001m');
  const [searchCl, setSearchCl] = useState<PayoutSearchCl>(PayoutSearchCl.REQUEST_DATE);
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [disbursementStatus, setDisbursementStatus] = useState<PayoutDisbursementStatus>(PayoutDisbursementStatus.ALL);
  const [minAmount, setMinAmount] = useState<number>();
	const [maxAmount, setMaxAmount] = useState<number>();

  const { mutateAsync: extensionPayoutList } = useExtensionPayoutListMutation();
  const { mutateAsync: extensionPayoutExcel } = useExtensionPayoutExcelMutation();
  
  useSetHeaderTitle('지급대행');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const onClickToNavigation = () => {
    navigate(PATHS.additionalService.payout.request);
  };
  const onClickToGoDetail = (tid?: string) => {
    if(!!tid){
      navigate(PATHS.additionalService.payout.detail, {
        state: {
          tid: tid
        }
      });
    }
  };

  const callExtensionPayoutList = (option?: {
    sortBy?: string, 
    val?: string
  }) => {
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
		let newMinAmount = minAmount;
		if(!!minAmount && typeof(minAmount) === 'string'){
			newMinAmount = parseInt(minAmount);
		}
		let newMaxAmount = maxAmount;
		if(!!maxAmount && typeof(maxAmount) === 'string'){
			newMaxAmount = parseInt(maxAmount);
		}
    let params: ExtensionPayoutListParams = {
      mid: mid,
      searchCl: searchCl,
      fromDate: fromDate,
      toDate: toDate,
      disbursementStatus: disbursementStatus,
      minAmount: minAmount,
      maxAmount: maxAmount,
      page: pageParam
    };
    extensionPayoutList(params).then((rs: ExtensionPayoutListResponse) => {
      setListItems(assembleData(rs.content));
    });
  };

  const callDownloadExcel = () => {
     let params: ExtensionPayoutExcelParams = {
      mid: mid,
      searchCl: searchCl,
      fromDate: fromDate,
      toDate: toDate,
      disbursementStatus: disbursementStatus,
      minAmount: minAmount,
      maxAmount: maxAmount,
    };
    extensionPayoutExcel(params).then((rs: ExtensionPayoutExcelResponse) => {

    });
  };

  const assembleData = (content: Array<PayoutContent>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let date;
        if(searchCl === PayoutSearchCl.REQUEST_DATE){
          date = content[i]?.requestDate?.substring(0, 8);
        }
        else if(searchCl === PayoutSearchCl.PROXY_DATE){
          date = content[i]?.settlementDate?.substring(0, 8);
        }
        let groupDate = moment(date).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };

  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callExtensionPayoutList({sortBy: sort});
  };
  const onClickToDisbursementStatus = (val: PayoutDisbursementStatus) => {
    setDisbursementStatus(val);
    callExtensionPayoutList({val: val});
  };


  useEffect(() => {
    callExtensionPayoutList();
  }, []);

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <section className="summary-section">
              <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">
                      50,000,000<span className="unit">원</span>
                    </span>
                  </div>
                </div>
              </div>
            </section>

            <section className="filter-section">
              <SortOptionsBox
                sortBy={ sortBy }
                onClickToSort={ onClickToSort }
              ></SortOptionsBox>
              <div className="excrow mr-0">
                <div className="full-menu-keywords no-padding">
                {
                  PayoutDisbursementStatusBtnGroup.map((value, index) => (
                    <span 
                      key={ `key-service-code=${ index }` }
                      className={ `keyword-tag ${(disbursementStatus === value.value)? 'active': ''}` }
                      onClick={ () => onClickToDisbursementStatus(value.value) }
                    >{ value.name }</span>
                  ))
                }
                </div>
              </div>
            </section>
            <div className="transaction-list">
              { getPayoutList() }  
              <div className="apply-row">
                <button 
                  className="btn-50 btn-blue flex-1"
                  onClick={ () => onClickToNavigation() }
                >지급대행 신청</button>
              </div>
            </div>
          </div>
        </div>
      </main>
      <PayoutFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        searchCl={ searchCl }
        fromDate={ fromDate }
        toDate={ toDate }
        disbursementStatus= { disbursementStatus }
        minAmount={ minAmount }
        maxAmount={ maxAmount }
        setMid={ setMid }
        setSearchCl={ setSearchCl }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setDisbursementStatus={ setDisbursementStatus }
        setMinAmount={ setMinAmount }
        setMaxAmount={ setMaxAmount }
      ></PayoutFilter>
    </>
  );
};