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 { ArsListContent, 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 } 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/filter/ars-filter';
import { useTranslation } from 'react-i18next';
import { useStore } from '@/shared/model/store';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';

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<ArsListContent>>([]);
  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 [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  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('신용카드 ARS 결제');
  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
      );
    });
  };

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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      const params: ExtensionArsDownloadExcelParams = {
        mid: mid,
        moid: moid,
        fromDate: fromDate,
        toDate: toDate,
        paymentStatus: paymentStatus,
        orderStatus: orderStatus,
        minAmount: minAmount,
        maxAmount: maxAmount,
        //email: selectedEmail
      };
      extensionArsDownloadExcel(params).then((rs: ExtensionArsDownloadExcelResponse) => {
        console.log('Excel Download Status:', rs);
      });
    }
    setEmailBottomSheetOn(false);
  };

  const onClickToNavigate = () => {
    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
  ]);

  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list = [];
    for (let i = 0; i < listItems.length; i++) {
      let item = listItems[i];
      if (!!item) {
        let orderDate = item?.orderDate || '';
        let itemDate = orderDate.substring(0, 8);
        if (!!itemDate) {
          if (i === 0) {
            date = itemDate;
          }
          if (date !== itemDate) {
            date = itemDate;
            if (list.length > 0) {
              rs.push(
                <ListDateGroup
                  additionalServiceCategory={AdditionalServiceCategory.Ars}
                  mid={mid}
                  key={date + '-' + i}
                  date={date}
                  items={list}
                ></ListDateGroup>
              );
            }
            list = [];
          }
          list.push(item);
        }
      }
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.Ars}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list as any}
        ></ListDateGroup>
      );
    }
    return rs;
  }

  // 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="필터"
                    onClick={() => onClickToOpenFilter()}
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt="검색옵션"
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label="다운로드"
                  onClick={() => onClickToOpenEmailBottomSheet()}
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                  />
                </button>
              </div>
            </section>

            <section className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
              ></SortTypeBox>
              <div className="excrow mr-0">
                <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>
            </section>

            <section className="transaction-list">
              { getListDateGroup() }
            </section>
            <div ref={ setTarget }></div>
          </div>
        </div>
        <div className="apply-row">
          <button
            className="btn-50 btn-blue flex-1"
            onClick={() => onClickToNavigate()}
          >결제 신청</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>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};