import moment from 'moment';
import { useEffect, useState } from 'react';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { SmsPaymentDetailResend } from '@/entities/additional-service/ui/sms-payment/sms-payment-detail-resend';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } from '@/entities/common/model/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { SmsPaymentListItem, SmsPaymentSearchCl, SmsCl, ExtensionSmsDetailResponse, ExtensionSmsPaymentListParams } from '@/entities/additional-service/model/sms-payment/types';
import { useExtensionSmsListMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-list-mutation';
import { useExtensionSmsDownloadExcelMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-download-excel-mutation';
import { SmsPaymentList } from '@/entities/additional-service/ui/sms-payment/sms-payment-list';
import { SmsPaymentFilter } from '@/entities/additional-service/ui/sms-payment/sms-payment-filter';
import { useExtensionSmsDetailMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-detail-mutation';
import { useStore } from '@/shared/model/store';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
import { PATHS } from '@/shared/constants/paths';
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 SmsPaymentPage = () => {
  const { navigate } = useNavigate();
  const userMid = useStore.getState().UserStore.mid;

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

  const [bottomSmsPaymentDetailResendOn, setBottomSmsPaymentDetailResendOn] = useState<boolean>(false)

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [listItems, setListItems] = useState<Array<SmsPaymentListItem>>([]);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [mid, setMid] = useState<string>(userMid);
  const [selectedTid, setSelectedTid] = useState<string>('');
  const [selectedMid, setSelectedMid] = useState<string>('');
  const [searchCl, setSearchCl] = useState<SmsPaymentSearchCl>(SmsPaymentSearchCl.BUYER_NAME)
  const [searchValue, setSearchValue] = useState<string>('')
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [smsCl, setSmsCl] = useState<SmsCl>(SmsCl.ALL);
  const [smsDetailData, setSmsDetailData] = useState<ExtensionSmsDetailResponse | null>(null);
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const { mutateAsync: smsPaymentList } = useExtensionSmsListMutation();
  const { mutateAsync: downloadExcel } = useExtensionSmsDownloadExcelMutation();
  const { mutateAsync: detail } = useExtensionSmsDetailMutation();
  
  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('SMS 결제 통보');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });
  const callList = (type?: string) => {
    setOnActionIntersect(false);
    let listParams: ExtensionSmsPaymentListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      fromDate: fromDate,
      toDate: toDate,
      smsCl: smsCl,
      page: pageParam
    }
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    smsPaymentList(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 callDetail = (selectedMid: string, selectedTid: string) => {
    console.log('Selected Mid: ', selectedMid, 'Selected Tid: ', selectedTid);
    detail({
      mid: selectedMid,
      tid: selectedTid
    }).then((rs) => {
      setSmsDetailData(rs);
    })
  }

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

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

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


  const onClickToShowDetail = (itemMid: string, itemTid: string) => {
    setSelectedMid(itemMid);
    setSelectedTid(itemTid);
    callDetail(itemMid, itemTid);
    setBottomSmsPaymentDetailResendOn(true);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    fromDate,
    toDate,
    smsCl
  ]);

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <section className="summary-section no-border">
              <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="필터"
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt="검색옵션"
                      onClick={() => onClickToOpenFilter()}
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label="다운로드"
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                    onClick={() => onClickToOpenEmailBottomSheet()}
                  />
                </button>
              </div>
            </section>
            <div className="detail-divider"></div>
            <SmsPaymentList
              listItems={listItems}
              additionalServiceCategory={AdditionalServiceCategory.SMSPayment}
              mid={mid}
              onResendClick={onClickToShowDetail}
            ></SmsPaymentList>
          </div>
        </div>
      </main>

      <SmsPaymentDetailResend
        bottomSmsPaymentDetailResendOn={bottomSmsPaymentDetailResendOn}
        setBottomSmsPaymentDetailResendOn={setBottomSmsPaymentDetailResendOn}
        smsDetailData={smsDetailData}
        mid={selectedMid}
        tid={selectedTid}
      ></SmsPaymentDetailResend>

      <SmsPaymentFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        fromDate={fromDate}
        toDate={toDate}
        smsCl={smsCl}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setSmsCl={setSmsCl}
      ></SmsPaymentFilter>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};