import moment from 'moment';
import { useEffect, useState } from 'react';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { PATHS } from '@/shared/constants/paths';
import { useExtensionKeyinDownloadExcelMutation } from '@/entities/additional-service/api/use-extension-keyin-download-excel-mutation';
import { KeyInPaymentFilter } from '@/entities/additional-service/ui/key-in-payment/filter/key-in-payment-filter';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { SortTypeKeys } from '@/entities/common/model/types';
import { useExtensionKeyinListMutation } from '@/entities/additional-service/api/use-extension-keyin-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { KeyInPaymentList } from '@/entities/additional-service/ui/key-in-payment/key-in-payment-list';
import { useStore } from '@/shared/model/store';
import { KeyInPaymentListItem, KeyInPaymentTransactionStatus } from '@/entities/additional-service/model/key-in/types';

// contant로 옮기기
const requestStatusBtnGroup = [
  { name: '전체', value: KeyInPaymentTransactionStatus.ALL },
  { name: '승인', value: KeyInPaymentTransactionStatus.APPROVAL },
  { name: '전취소', value: KeyInPaymentTransactionStatus.PRE_CANCEL },
  { name: '후취소', value: KeyInPaymentTransactionStatus.POST_CANCEL }
];

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

  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [startDate, setStartDate] = useState(moment().format('YYYY-MM-DD'));
  const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));
  const [transactionStatus, setTransactionStatus] = useState<KeyInPaymentTransactionStatus>(KeyInPaymentTransactionStatus.ALL)
  const [minAmount, setMinAmount] = useState<number>();
  const [maxAmount, setMaxAmount] = useState<number>();


  useSetHeaderTitle('KEY-IN 결제');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: keyinList } = useExtensionKeyinListMutation();
  const { mutateAsync: downloadExcel } = useExtensionKeyinDownloadExcelMutation();

  const callList = (option?: {
    sortType?: SortTypeKeys,
    val?: string
  }) => {
    pageParam.sortType = (option?.sortType) ? option.sortType : sortType;
    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 listParams = {
      mid: mid,
      fromDate: startDate,
      toDate: endDate,
      paymentStatus: transactionStatus,
      minAmount: newMinAmount,
      maxAmount: newMaxAmount,
      page: pageParam
    };

    console.log('Request Info: ', listParams);

    keyinList(listParams).then((rs) => {
      setListItems(assembleData(rs.content));
    });
  }

  const assembleData = (content: Array<KeyInPaymentListItem>) => {
    console.log('rs.content:', content);
    let data: any = {};
    if (content && content.length > 0) {
      for(let i = 0; i < content?.length; i++){
        let paymentDate = content[i]?.paymentDate?.substring(0, 8);
        let groupDate = moment(paymentDate).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    console.log('Data : ', data);
    return data;
  };


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

  const onClickToDownloadExcel = () => {
    let newMinAmount = minAmount;
    if(!!minAmount && typeof (minAmount) === 'string'){
      newMinAmount = parseInt(minAmount);
    }
    let newMaxAmount = maxAmount;
    if(!!maxAmount && typeof (maxAmount) === 'string'){
      newMaxAmount = parseInt(maxAmount);
    }
    downloadExcel({
      mid: mid,
      fromDate: startDate,
      toDate: endDate,
      paymentStatus: transactionStatus,
      minAmount: newMinAmount,
      maxAmount: newMaxAmount
    }).then((rs) => {
      console.log('Excel Dowload Status : ' + rs.status);
    });
  };

  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
    callList({
      sortType: sort
    });
  };

  const onClickToTransactionStatus = (val: KeyInPaymentTransactionStatus) => {
    console.log('TransactionStatus Test: ', val);
    setTransactionStatus(val);
    callList({ 
      val: val 
    });
  };

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

  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(startDate).format('YYYY.MM.DD') + '-' + moment(endDate).format('YYYY.MM.DD')}
                    readOnly={true}
                  />
                  <button
                    className="filter-btn"
                    aria-label="필터"
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt="검색옵션"
                      onClick={() => onClickToOpenFilter()}
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label="다운로드"
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                    onClick={() => onClickToDownloadExcel()}
                  />
                </button>
              </div>
            </section>

            <div className="filter-section">
              <SortTypeBox
                sortType={ sortType }
                onClickToSort={ onClickToSort }
              ></SortTypeBox>
              <div className="excrow">
                <div className="full-menu-keywords no-padding">
                  {
                    requestStatusBtnGroup.map((value, index) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(transactionStatus === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToTransactionStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <KeyInPaymentList
              listItems={listItems}
              additionalServiceCategory={AdditionalServiceCategory.KeyInPayment}
              mid={mid}
            ></KeyInPaymentList>
          </div>
        </div>
      </main>
      <KeyInPaymentFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        startDate={startDate}
        endDate={endDate}
        transactionStatus={transactionStatus}
        minAmount={minAmount}
        maxAmount={maxAmount}
        setMid={setMid}
        setStartDate={setStartDate}
        setEndDate={setEndDate}
        setTransactionStatus={setTransactionStatus}
        setMinAmount={setMinAmount}
        setMaxAmount={setMaxAmount}
      ></KeyInPaymentFilter>
    </>
  );
};