import moment from 'moment';

import { useEffect, useState } from 'react';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { ListFilter } from './filter/list-filter';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { SortByKeys } from '@/entities/common/model/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { 
  VatReturnListContent, 
  VatReturnListParams, 
  VatReturnReceiptType, 
  VatReturnTargetType 
} from '../model/types';
import { useVatReturnListMutation } from '../api/use-vat-return-list-mutation';
import { ListDateGroup } from './list-date-group';

export const ListWrap = () => {
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<VatReturnListContent>>>({});
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest00m');
  const [startDate, setStartDate] = useState(moment().subtract(1, 'month').format('YYYY.MM'));
	const [endDate, setEndDate] = useState(moment().format('YYYY.MM'));
  const [receiptType, setReceiptType] = useState<VatReturnReceiptType>(VatReturnReceiptType.ALL);
  const [targetType, setTargetType] = useState<VatReturnTargetType>(VatReturnTargetType.ALL);

  const { mutateAsync: vatReturnList } = useVatReturnListMutation();

  const callList = () => {
    let strStartDate = moment(startDate).format('YYYYMM');
    let newStartDate = moment(strStartDate+'01').format('YYYY-MM-DD');

    let strEndtDate = moment(endDate).format('YYYYMM');
    let lastDate = moment(endDate).endOf('month').date();
    let newEndDate = moment(strEndtDate+lastDate).format('YYYY-MM-DD');

    let params: VatReturnListParams = {
      mid: mid,
      startDate: newStartDate,
      endDate: newEndDate,
      receiptType: receiptType,
      targetType: targetType,
    };
    vatReturnList(params).then((rs) => {
      setListItems(assembleData(rs.content));
    });
    
  };
  
  const onClickToOpenFIlter = () => {
    setFilterOn(true);
  };
  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
  };

  useEffect(() => {
    callList();
  }, [mid, startDate, endDate, receiptType, targetType]);

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

  const assembleData = (content: Array<VatReturnListContent>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let groupDate = moment(content[i]?.issueDate).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };
  return (
    <>
      <div className="summary-section pt-30">
        <div className="credit-controls">
          <div>
            <input 
              type="text" 
              className="credit-period" 
              value={moment(startDate).format('YYYY.MM.DD') + '-' + moment(endDate).format('YYYY.MM.DD')} 
              readOnly={ true }
            />
            <button 
              className="filter-btn"
              onClick={ () => onClickToOpenFIlter() }
            >
              <img 
                src={ IMAGE_ROOT + '/ico_setting.svg' }
                alt="검색옵션"
              />
            </button>
          </div>
          <button className="download-btn">
            <img 
              src={ IMAGE_ROOT + '/ico_download.svg' }
              alt="다운로드"
            />
          </button>
        </div>
      </div>
      <div className="filter-section mt-10">
        <SortOptionsBox
          sortBy={ sortBy }
          onClickToSort={ onClickToSort }
        ></SortOptionsBox>
      </div>
      <div className="transaction-list">
      { getListDateGroup() }
      </div>
      <div className="apply-row bottom-padding">
        <button className="btn-50 btn-blue flex-1">수기발행</button>
      </div>
      <ListFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        startDate={ startDate }
        endDate={ endDate }
        receiptType={ receiptType }
        targetType={ targetType }
        setMid={ setMid }
        setStartDate={ setStartDate }
        setEndDate={ setEndDate }
        setReceiptType={ setReceiptType }
        setTargetType={ setTargetType }
      ></ListFilter>
    </>
  );
};