import moment from 'moment';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useState, useEffect } from "react";
import { LinkPaymentWaitSendFilter } from "./filter/link-payment-pending-send-filter";
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { LinkPaymentWaitList } from "./link-payment-wait-list";
import { AdditionalServiceCategory } from "../../model/types";
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { useExtensionLinkPayWaitListMutation } from '../../api/link-payment/use-extension-link-pay-wait-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionLinkPayWaitDownloadExcelMutation } from '../../api/link-payment/use-extension-link-pay-wait-download-excel-mutation';
import { useStore } from '@/shared/model/store';
import { LinkPaymentProcessStatus, LinkPaymentSearchCl, LinkPaymentSendMethod, LinkPaymentSendStatus, LinkPaymentWaitListItem } from '../../model/link-pay/types';
import { getProcessStatusBtnGroup } from '../../model/link-pay/constant';
import { useExtensionLinkPayWaitDeleteMutation } from '../../api/link-payment/use-extension-link-pay-wait-delete-mutation';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useTranslation } from 'react-i18next';



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

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [mid, setMid] = useState<string>(userMid);
  const [searchType, setSearchType] = useState<LinkPaymentSearchCl>(LinkPaymentSearchCl.PHONE)
  const [searchValue, setSearchValue] = useState<string>('');
  const [startDate, setStartDate] = useState(moment().format('YYYYMMDD'));
  const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
  const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(LinkPaymentSendMethod.ALL);
  const [processStatus, setProcessStatus] = useState<LinkPaymentProcessStatus>(LinkPaymentProcessStatus.ALL);
  const [listItems, setListItems] = useState<Array<LinkPaymentWaitListItem>>([]);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const { mutateAsync: pendingSendList } = useExtensionLinkPayWaitListMutation();
  const { mutateAsync: downloadExcel } = useExtensionLinkPayWaitDownloadExcelMutation();
  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 onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToNavigate = () => {
    navigate(PATHS.additionalService.linkPayment.request)
  }

  const callList = (type?: string) => {
    setOnActionIntersect(false);
    let listParams = {
      mid: mid,
      searchCl: searchType,
      searchValue: searchValue,
      fromDate: startDate,
      toDate: endDate,
      sendMethod: sendMethod,
      processStatus: processStatus,
      page: {
				...pageParam,
				...{ sortType: sortType }
			}
    }
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }
    
    pendingSendList(listParams).then((rs) => {
      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
      );
    });
  };

  const onClickToOpenEmailBottomSheet = () => {
    setEmailBottomSheetOn(true);
  };

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      downloadExcel({
        mid: mid,
        email: selectedEmail,
        searchCl: searchType,
        searchValue: searchValue,
        fromDate: startDate,
        toDate: endDate,
        sendMethod: sendMethod,
        processStatus: processStatus,
      }).then((rs) => {
        console.log('Excel Download Status: ' + rs.status);
      });
    }
    setEmailBottomSheetOn(false);
  };

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

  const onClickSendingStatus = (val: LinkPaymentProcessStatus) => {
    setProcessStatus(val);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    searchType,
    searchValue,
    startDate,
    endDate,
    sendMethod,
    processStatus,
    sortType
  ]);

  return (
    <>
      <section className="summary-section pt-30">
        <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">
              <img
                src={IMAGE_ROOT + '/ico_setting.svg'}
                alt={t('common.searchOptions')}
                onClick={() => onClickToOpenFilter()}
              />
            </button>
          </div>
          <button
            className="download-btn"
            aria-label={t('common.download')}
            onClick={() => onClickToOpenEmailBottomSheet()}
          >
            <img
              src={IMAGE_ROOT + '/ico_download.svg'}
              alt={t('common.download')}
            />
          </button>
        </div>
      </section>

      <div className="filter-section">
        <SortTypeBox
          sortType={sortType}
          onClickToSort={onClickToSort}
        ></SortTypeBox>
        <div className="excrow">
          <div className="full-menu-keywords no-padding">
            {
              getProcessStatusBtnGroup(t).map((value: any, index: number) => (
                <span
                  key={`key-service-code=${index}`}
                  className={`keyword-tag ${(processStatus === value.value) ? 'active' : ''}`}
                  onClick={() => onClickSendingStatus(value.value)}
                >{value.name}</span>
              ))
            }
          </div>
        </div>
      </div>

      <LinkPaymentWaitList
        listItems={listItems}
        additionalServiceCategory={AdditionalServiceCategory.LinkPaymentWait}
        mid={mid}
      ></LinkPaymentWaitList>
      <div ref={ setTarget }></div>
      <div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={() => onClickToNavigate()}
        >{t('additionalService.linkPayment.applyRequest')}</button>
      </div>
      <LinkPaymentWaitSendFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchType}
        searchKeyword={searchValue}
        startDate={startDate}
        endDate={endDate}
        sendMethod={sendMethod}
        processStatus={processStatus}
        setMid={setMid}
        setSearchType={setSearchType}
        setSearchKeyword={setSearchValue}
        setStartDate={setStartDate}
        setEndDate={setEndDate}
        setSendMethod={setSendMethod}
        setProcessStatus={setProcessStatus}
      ></LinkPaymentWaitSendFilter>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
}