import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { HeaderType, SortByKeys } from '@/entities/common/model/types';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { ArsListContent, ExtensionArsDownloadExcelParams, ExtensionArsDownloadExcelResponse, ExtensionArsListParams, ExtensionArsListResponse, OrderStatus, PaymentStatus } from '@/entities/additional-service/model/ars/types';
import { useExtensionArsListMutation } from '@/entities/additional-service/api/ars/use-extension-ars-list-mutation';
import moment from 'moment';
import { useExtensionArsDownloadExcelMutation } from '@/entities/additional-service/api/ars/use-extension-ars-download-excel-mutation';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { ArsPaymentStatusBtnGroup } from '@/entities/additional-service/model/ars/constant';
import { ArsFilter } from '@/entities/additional-service/ui/filter/ars-filter';

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

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<ArsListContent>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest001m');
  const [moid, setMoid] = useState<string>('');
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [paymentStatus, setPaymentStatus] = useState<PaymentStatus>(PaymentStatus.ALL);
  const [orderStatus, setOrderStatus] = useState<OrderStatus>(OrderStatus.ALL);
  const [minAmount, setMinAmount] = useState<number>();
  const [maxAmount, setMaxAmount] = useState<number>();

  const { mutateAsync: extensionArsList } = useExtensionArsListMutation();
  const { mutateAsync: extensionArsDownloadExcel } = useExtensionArsDownloadExcelMutation();
  
  useSetHeaderTitle('신용카드 ARS 결제');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

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

    let params: ExtensionArsListParams = {
      mid: mid,
      moid: moid,
      fromDate: fromDate,
      toDate: toDate,
      paymentStatus: paymentStatus,
      orderStatus: orderStatus,
      minAmount: minAmount,
      maxAmount: maxAmount,
      page: pageParam
    };
    extensionArsList(params).then((rs: ExtensionArsListResponse) => {
      setListItems(assembleData(rs.content));
    });
  };

  const callDownloadExcel = () => {
    let params: ExtensionArsDownloadExcelParams = {
      mid: mid,
      moid: moid,
      fromDate: fromDate,
      toDate: toDate,
      paymentStatus: paymentStatus,
      orderStatus: orderStatus,
      minAmount: minAmount,
      maxAmount: maxAmount,
    };
    extensionArsDownloadExcel(params).then((rs: ExtensionArsDownloadExcelResponse) => {

    });
  };

  const assembleData = (content: Array<ArsListContent>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let date = content[i]?.paymentDate?.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 onClickToNavigate = () => {
    navigate(PATHS.additionalService.ars.request);
  };

  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callList({sortBy: sort});
  };
  const onClickToPaymentStatus = (val: PaymentStatus) => {
    setPaymentStatus(val);
    callList({val: val});
  };

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

  const getArsList = () => {
    let rs = [];
    if(Object.keys(listItems).length > 0){
      for (const [key, value] of Object.entries(listItems)) {
        rs.push(
          <ListDateGroup
            additionalServiceCategory={ AdditionalServiceCategory.Ars }
            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>
            </section>

            <section className="filter-section">
              <SortOptionsBox
                sortBy={ sortBy }
                onClickToSort={ onClickToSort }
              ></SortOptionsBox>
              <div className="excrow mr-0">
                <div className="full-menu-keywords no-padding">
                  {
                    ArsPaymentStatusBtnGroup.map((value, index) => (
                      <span 
                        key={ `key-service-code=${ index }` }
                        className={ `keyword-tag ${(paymentStatus === value.value)? 'active': ''}` }
                        onClick={ () => onClickToPaymentStatus(value.value) }
                      >{ value.name }</span>
                    ))
                  }
                </div>
              </div>
            </section>
            
            <section className="transaction-list">
              { getArsList() }
              <div className="apply-row">
                <button 
                  className="btn-50 btn-blue flex-1"
                  onClick={ () => onClickToNavigate() }
                >결제 신청</button>
              </div>
            </section>
          </div>
        </div>
      </main>
      <ArsFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        moid={ moid }
        fromDate={ fromDate }
        toDate={ toDate }
        paymentStatus={ paymentStatus }
        orderStatus={ orderStatus }
        minAmount={ minAmount }
        maxAmount={ maxAmount }
        setMid={ setMid }
        setMoid={ setMoid }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setPaymentStatus={ setPaymentStatus }
        setOrderStatus={ setOrderStatus }
        setMinAmount={ setMinAmount }
        setMaxAmount={ setMaxAmount }
      ></ArsFilter>
    </>
  );
};