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 { DefaultRequestPagination, 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, KeyInPaymentStatus, KeyInPaymentTansactionType } from '@/entities/additional-service/model/key-in/types';
import { getKeyInPaymentPaymentStatusBtnGroup } from '@/entities/additional-service/model/key-in/constant';
import { DownloadBottomSheet, DownloadSelectedMode } from '@/entities/common/ui/download-bottom-sheet';
import { useTranslation } from 'react-i18next';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { checkGrant } from '@/shared/lib/check-grant';
import { showAlert } from '@/widgets/show-alert';
import { snackBar } from '@/shared/lib';

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

  // 권한 체크
  const { hasAccess, AccessDeniedDialog } = useExtensionAccessCheck({
    extensionCode: 'KEYIN'
  });

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<KeyInPaymentListItem>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [startDate, setStartDate] = useState(moment().format('YYYYMMDD'));
  const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
  const [transactionType, setTransactionType] = useState<KeyInPaymentTansactionType>(KeyInPaymentTansactionType.ALL)
  const [status, setStatus] = useState<KeyInPaymentStatus>(KeyInPaymentStatus.ALL);
  const [minAmount, setMinAmount] = useState<number>();
  const [maxAmount, setMaxAmount] = useState<number>();

  const [downloadBottomSheetOn, setDownloadBottomSheetOn] = useState<boolean>(false);

  useSetHeaderTitle(t('additionalService.keyIn.title'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: keyinList } = useExtensionKeyinListMutation();
  const { mutateAsync: downloadExcel } = useExtensionKeyinDownloadExcelMutation();
  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 = (type?: string) => {
    setOnActionIntersect(false);
    let listParams = {
      mid: 'nictest02m',
      startDate: startDate,
      endDate: endDate,
      transactionType: transactionType,
      status: status,
      minAmount: minAmount,
      maxAmount: maxAmount,
      page: {
				...pageParam,
				...{ sortType: sortType }
			}
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    keyinList(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
      );
    }).catch((e: any) => {
      if(e.response?.data?.error?.message){
        snackBar(e.response?.data?.error?.message);
        return;
      }
    });
  }

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

  const onClickToOpenDownloadBottomSheet = () => {
    if (!checkGrant(56, 'D')) {
      showAlert(t('common.nopermission'));
      return;
    }
    setDownloadBottomSheetOn(true);
  };

  // 엑셀 다운로드
  const onRequestDownloadExcel = (
		selectedMode: DownloadSelectedMode,
		userEmail?: string
	) => {
    if(selectedMode === DownloadSelectedMode.EMAIL
      && userEmail
    ){
      downloadExcel({
        mid: mid,
        fromDate: startDate,
        toDate: endDate,
        paymentStatus: transactionType,
        minAmount: minAmount,
        maxAmount: maxAmount,
        email: userEmail
      }).then((rs) => {
        console.log('Excel Download Status:', rs.status);
      }).catch((e: any) => {
        if(e.response?.data?.error?.message){
          snackBar(e.response?.data?.error?.message);
          return;
        }
      });
    }
  };

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

  const onClickToPaymentStatus = (val: KeyInPaymentTansactionType) => {
    setTransactionType(val);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    startDate,
    endDate,
    transactionType,
    minAmount,
    maxAmount,
    sortType
  ]);

  if (!hasAccess) {
    return <AccessDeniedDialog />;
  }


  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="다운로드"
                  onClick={ onClickToOpenDownloadBottomSheet }
                >
                  <img
                    src={ IMAGE_ROOT + '/ico_download.svg' }
                    alt="다운로드"
                  />
                </button>
              </div>
            </section>

            <div className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
              ></SortTypeBox>
              <div className="excrow">
                <div className="full-menu-keywords no-padding">
                  {
                    getKeyInPaymentPaymentStatusBtnGroup(t).map((value: any, index: number) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(transactionType === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToPaymentStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <KeyInPaymentList
              listItems={listItems}
              additionalServiceCategory={AdditionalServiceCategory.KeyInPayment}
              mid={mid}
              onClickToOpenFilter={ onClickToOpenFilter }
              onClickToOpenDownloadBottomSheet={ onClickToOpenDownloadBottomSheet }
            ></KeyInPaymentList>
            <div ref={ setTarget }></div>
          </div>
        </div>
      </main>
      <KeyInPaymentFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        startDate={startDate}
        endDate={endDate}
        transactionStatus={transactionType}
        minAmount={minAmount}
        maxAmount={maxAmount}
        setMid={setMid}
        setStartDate={setStartDate}
        setEndDate={setEndDate}
        setTransactionStatus={setTransactionType}
        setMinAmount={setMinAmount}
        setMaxAmount={setMaxAmount}
      ></KeyInPaymentFilter>
      { !!downloadBottomSheetOn &&
        <DownloadBottomSheet
          bottomSheetOn={ downloadBottomSheetOn }
          setBottomSheetOn={ setDownloadBottomSheetOn }
          imageMode={ false }
          emailMode={ true }
          sendRequest={ onRequestDownloadExcel }
        ></DownloadBottomSheet>
      }
    </>
  );
};