import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { JSX, useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { ArsListItem, 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, DetailData } from '@/entities/additional-service/model/types';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { getArsPaymentStatusBtnGroup } from '@/entities/additional-service/model/ars/constant';
import { ArsFilter } from '@/entities/additional-service/ui/ars/filter/ars-filter';
import { useTranslation } from 'react-i18next';
import { useStore } from '@/shared/model/store';
import { DownloadBottomSheet, DownloadSelectedMode } from '@/entities/common/ui/download-bottom-sheet';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { ArsList } from '@/entities/additional-service/ui/ars/ars-list';
import { ArsDetail } from '@/entities/additional-service/ui/ars/detail/ars-detail';
import { checkGrant } from '@/shared/lib/check-grant';
import { showAlert } from '@/widgets/show-alert';
import { snackBar } from '@/shared/lib';

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

  const userMid = useStore.getState().UserStore.mid;

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

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<ArsListItem>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  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 [downloadBottomSheetOn, setDownloadBottomSheetOn] = useState<boolean>(false);

  const [detailOn, setDetailOn] = useState<boolean>(false);
  const [detailMid, setDetailMid] = useState<string>('');
  const [detailTid, setDetailTid] = useState<string>('');

  const { mutateAsync: extensionArsList } = useExtensionArsListMutation();
  const { mutateAsync: extensionArsDownloadExcel } = useExtensionArsDownloadExcelMutation();
  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
  });

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

  const callList = (type?: string) => {
    setOnActionIntersect(false);
    let listParams: ExtensionArsListParams = {
      mid: mid,
      moid: moid,
      fromDate: fromDate,
      toDate: toDate,
      paymentStatus: paymentStatus,
      orderStatus: orderStatus,
      minAmount: minAmount,
      maxAmount: maxAmount,
      page: {
        ...pageParam,
        ...{ sortType: sortType }
      }
    };
    if (type !== 'page' && listParams.page) {
      listParams.page.cursor = null;
    }

    extensionArsList(listParams).then((rs: ExtensionArsListResponse) => {
      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 onClickToOpenDownloadBottomSheet = () => {
    if (!checkGrant(52, 'D')) {
      showAlert(t('common.nopermission'));
      return;
    }
    setDownloadBottomSheetOn(true);
  };

  const onRequestDownloadExcel = (
		selectedMode: DownloadSelectedMode,
		userEmail?: string
	) => {
    if(selectedMode === DownloadSelectedMode.EMAIL
      && userEmail
    ){
      const params: ExtensionArsDownloadExcelParams = {
        mid: mid,
        moid: moid,
        fromDate: fromDate,
        toDate: toDate,
        paymentStatus: paymentStatus,
        orderStatus: orderStatus,
        minAmount: minAmount,
        maxAmount: maxAmount,
        email: userEmail
      };
      extensionArsDownloadExcel(params).then((rs: ExtensionArsDownloadExcelResponse) => {
        console.log('Excel Download Status:', rs);
      }).catch((e: any) => {
        if(e.response?.data?.error?.message){
          snackBar(e.response?.data?.error?.message);
          return;
        }
      });
    }
  };

  const setDetailData = (detailData: DetailData) => {
    setDetailOn(detailData.detailOn);
    if (detailData.mid) {
      setDetailMid(detailData.mid);
    }
    if (detailData.tid) {
      setDetailTid(detailData.tid);
    }
  };

  const onClickToNavigate = () => {
    if (!checkGrant(52, 'X')) {
      showAlert(t('common.nopermission'));
      return;
    }
    navigate(PATHS.additionalService.ars.request, {
      state: { mid }
    });
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };
  const onClickToPaymentStatus = (val: PaymentStatus) => {
    setPaymentStatus(val);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    moid,
    fromDate,
    toDate,
    paymentStatus,
    orderStatus,
    minAmount,
    maxAmount,
    sortType
  ]);

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

  return (
    <>
      <main>
        <div className="tab-content pb-86">
          <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={t('filter.filter')}
                    onClick={ onClickToOpenFilter }
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt={t('common.searchOptions')}
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label={t('common.download')}
                  onClick={ onClickToOpenDownloadBottomSheet }
                >
                  <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">
                  {
                    getArsPaymentStatusBtnGroup(t).map((value: any, index: number) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(paymentStatus === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToPaymentStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>

            <ArsList
              additionalServiceCategory={AdditionalServiceCategory.Ars}
              listItems={listItems}
              mid={mid}
              setDetailData={setDetailData}
            ></ArsList>
            <div ref={setTarget}></div>
          </div>
        </div>
        <div className="apply-row">
          <button
            className="btn-50 btn-blue flex-1"
            onClick={onClickToNavigate}
          >{t('additionalService.ars.paymentRequest')}</button>
        </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>
      <ArsDetail
        detailOn={detailOn}
        setDetailOn={setDetailOn}
        mid={detailMid}
        tid={detailTid}
      ></ArsDetail>
      { !!downloadBottomSheetOn &&
        <DownloadBottomSheet
          bottomSheetOn={ downloadBottomSheetOn }
          setBottomSheetOn={ setDownloadBottomSheetOn }
          imageMode={ false }
          emailMode={ true }
          sendRequest={ onRequestDownloadExcel }
        ></DownloadBottomSheet>
      }
    </>
  );
};