import moment from 'moment';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { ListFilter } from './filter/list-filter';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import {
  VatReturnListContent,
  VatReturnListParams,
  VatReturnListResponse,
  VatReturnReceiptType,
  VatReturnTargetType
} from '../model/types';
import { useVatReturnListMutation } from '../api/use-vat-return-list-mutation';
import { ListDateGroup } from './list-date-group';
import { useStore } from '@/shared/model/store';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';

export const ListWrap = () => {
  const { t } = useTranslation();
  const userMid = useStore.getState().UserStore.mid;

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<VatReturnListContent>>([]);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [startMonth, setStartMonth] = useState<string>(moment().subtract(1, 'month').format('YYYYMM'));
	const [endMonth, setEndMonth] = useState<string>(moment().format('YYYYMM'));
  const [receiptType, setReceiptType] = useState<VatReturnReceiptType>(VatReturnReceiptType.ALL);
  const [targetType, setTargetType] = useState<VatReturnTargetType>(VatReturnTargetType.ALL);

  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const { mutateAsync: vatReturnList } = useVatReturnListMutation();
  const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if(entry.isIntersecting){
        if(onActionIntersect && !!pageParam.cursor){
          setOnActionIntersect(false);
          callList('page');
        } 
      }
    });
  };

  const { setTarget } = useIntersectionObserver({ 
    threshold: 1, 
    onIntersect 
  });

  const callList = async(type?: string) => {
    setOnActionIntersect(false);
    let params: VatReturnListParams = {
      mid: mid,
      startMonth: startMonth,
      endMonth: endMonth,
      receiptType: receiptType,
      targetType: targetType,
      page: {
        ...pageParam,
        ...{ sortType: sortType }
      }
    };
    
    vatReturnList(params).then((rs: VatReturnListResponse) => {
      if(type === 'page'){
        setListItems([
          ...listItems,
          ...rs.content
        ]);
      }
      else{
        setListItems(rs.content);
      }
      if(rs.hasNext 
        && rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      ){
        setPageParam({
          ...pageParam,
          ...{ cursor: rs.nextCursor }
        });
      }
      else{
        setPageParam({
          ...pageParam,
          ...{ cursor: null }
        });
      }
      setOnActionIntersect(
        !!rs.hasNext 
        && rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      );
    }).catch((e: any) => {
      console.log(e)
      return;
    });
  };
  
  const onClickToOpenFIlter = () => {
    setFilterOn(true);
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };
  const onClickToDownloadExcel = () => {
    setEmailBottomSheetOn(true);
  };
  const onRequestDownloadExcel = (userEmail?: string) => {

	};

  useEffect(() => {
    callList();
  }, [
    mid, startMonth, endMonth, 
    receiptType, targetType, sortType
  ]);

  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list: Array<VatReturnListContent> = [];

    for(let i=0;i<listItems.length;i++){
      let item = listItems[i];
      if(!!item){
        let issueDateTime = item?.issueDate;
        let issueDate = issueDateTime?.substr(0, 8);
        if(!!issueDate){
          if(i === 0){
            date = issueDate;
          }
          if(date !== issueDate){
            if(list.length > 0){
              rs.push(
                <ListDateGroup
                  key={ date + '-' + i }
                  date={ date }
                  items={ list }
                ></ListDateGroup>
              );
            }
            date = issueDate;
            list = [];
          }
          list.push(item);
        }
      }
    }
    if(list.length > 0){
      rs.push(
        <ListDateGroup
          key={ date + '-last' }
          date={ date }
          items={ list }
        ></ListDateGroup>
      );
    }
    return rs;
  };
  
  return (
    <>
      <div className="summary-section pt-30">
        <div className="credit-controls">
          <div>
            <input 
              type="text" 
              className="credit-period" 
              value={ moment(startMonth+'01').format('YYYY.MM') + '-' + moment(endMonth+'01').format('YYYY.MM')} 
              readOnly={ true }
            />
            <button
              className="filter-btn"
              onClick={ () => onClickToOpenFIlter() }
            >
              <img
                src={ IMAGE_ROOT + '/ico_setting.svg' }
                alt={t('transaction.searchOptions')}
              />
            </button>
          </div>
          <button className="download-btn">
            <img
              src={ IMAGE_ROOT + '/ico_download.svg' }
              alt={t('transaction.download')}
              onClick={ onClickToDownloadExcel }
            />
          </button>
        </div>
      </div>
      <div className="filter-section mt-10">
        <SortTypeBox
          sortType={ sortType }
          onClickToSort={ onClickToSort }
        ></SortTypeBox>
      </div>
      <div className="transaction-list">
        { getListDateGroup() }
        <div ref={ setTarget }></div>
      </div>
      <ListFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        startMonth={ startMonth }
        endMonth={ endMonth }
        receiptType={ receiptType }
        targetType={ targetType }
        setMid={ setMid }
        setStartMonth={ setStartMonth }
        setEndMonth={ setEndMonth }
        setReceiptType={ setReceiptType }
        setTargetType={ setTargetType }
      ></ListFilter>
      { !!emailBottomSheetOn &&
        <EmailBottomSheet
          bottomSheetOn={ emailBottomSheetOn }
          setBottomSheetOn={ setEmailBottomSheetOn }
          imageSave={ false }
          sendEmail={ true }
          sendRequest={ onRequestDownloadExcel }
        ></EmailBottomSheet>
      }
    </>
  );
};