import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } 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,
  PayoutSearchDateType
} from '@/entities/additional-service/model/payout/types';
import { JSX, 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 { SortTypeBox } from '@/entities/common/ui/sort-type-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';
import { useStore } from '@/shared/model/store';

export const PayoutListPage = () => {
  const { navigate } = useNavigate();
  const userMid = useStore.getState().UserStore.mid;

  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<PayoutContent>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [searchDateType, setSearchDateType] = useState<PayoutSearchDateType>(PayoutSearchDateType.REQUEST_DATE);
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [status, setStatus] = useState<PayoutDisbursementStatus>(PayoutDisbursementStatus.ALL);
  const [minAmount, setMinAmount] = useState<number>(0);
	const [maxAmount, setMaxAmount] = useState<number>(50000000);

  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 callExtensionPayoutList = (option?: {
    sortType?: SortTypeKeys,
    status?: PayoutDisbursementStatus
  }) => {
		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,
      searchDateType: searchDateType,
      fromDate: fromDate,
      toDate: toDate,
      status: option?.status ?? status,
      minAmount: newMinAmount,
      maxAmount: newMaxAmount,
      page: pageParam
    };

    if(params.page){
      params.page.sortType = option?.sortType || sortType;
      setPageParam(params.page);
    }

    extensionPayoutList(params).then((rs: ExtensionPayoutListResponse) => {
      setListItems(rs.content);
    });
  };

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

    });
  };

  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
    callExtensionPayoutList({
      sortType: sort
    });
  };
  const onClickToDisbursementStatus = (val: PayoutDisbursementStatus) => {
    setStatus(val);
    callExtensionPayoutList({
      status: val
    });
  };

  useEffect(() => {
    callExtensionPayoutList();
  }, [
    mid,
    searchDateType,
    fromDate,
    toDate,
    status,
    minAmount,
    maxAmount
  ]);

  const getListDateGroup = () => {
    let rs: JSX.Element[] = [];
    let date = '';
    let list: PayoutContent[] = [];
    for (let i = 0; i < listItems.length; i++) {
      // requestDate 또는 settlementDate format: "20211018140420" (YYYYMMDDHHmmss)
      let itemDateStr = '';
      if (searchDateType === PayoutSearchDateType.REQUEST_DATE) {
        itemDateStr = listItems[i]?.requestDate || '';
      } else if (searchDateType === PayoutSearchDateType.SETTLEMENT_DATE) {
        itemDateStr = listItems[i]?.settlementDate || '';
      }
      let itemDate = itemDateStr.substring(0, 8);
      if (i === 0) {
        date = itemDate;
      }
      if (date !== itemDate) {
        // 날짜가 바뀌면 이전 리스트를 푸시 (날짜 업데이트 전에!)
        if (list.length > 0) {
          rs.push(
            <ListDateGroup
              additionalServiceCategory={AdditionalServiceCategory.Payout}
              mid={mid}
              key={date + '-' + i}
              date={date}
              items={list as any}
            ></ListDateGroup>
          );
        }
        date = itemDate;  // 그 다음에 날짜 업데이트
        list = [];
      }
      list.push(listItems[i] as any);
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.Payout}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list as any}
        ></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">
              <SortTypeBox
                sortType={ sortType }
                onClickToSort={ onClickToSort }
              ></SortTypeBox>
              <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 ${(status === value.value)? 'active': ''}` }
                      onClick={ () => onClickToDisbursementStatus(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={ () => onClickToNavigation() }
              >지급대행 신청</button>
            </div>
          </div>
        </div>
      </main>
      <PayoutFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        searchDateType={ searchDateType }
        fromDate={ fromDate }
        toDate={ toDate }
        status= { status }
        minAmount={ minAmount }
        maxAmount={ maxAmount }
        setMid={ setMid }
        setSearchDateType={ setSearchDateType }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setStatus={ setStatus }
        setMinAmount={ setMinAmount }
        setMaxAmount={ setMaxAmount }
      ></PayoutFilter>
    </>
  );
};