import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
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 {
  AlimtalkAlimCl,
  AlimtalkListContent,
  AlimtalkSearchCl,
  AlimTalkSendCl,
  AlimtalkSendType,
  ExtensionAlimtalkDownloadExcelParams,
  ExtensionAlimtalkDownloadExcelResponse,
  ExtensionAlimtalkListParams,
  ExtensionAlimtalkListResponse,
  ServiceCode
} from '@/entities/additional-service/model/alimtalk/types';
import moment from 'moment';
import { useExtensionAlimtalkListMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-list-mutation';
import { useExtensionAlimtalkDownloadExcelMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-download-excel-mutation';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import { AlimtalkFilter } from '@/entities/additional-service/ui/filter/alimtalk-filter';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';

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

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

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [listItems, setListItems] = useState<Array<AlimtalkListContent>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [searchCl, setSearchCl] = useState<AlimtalkSearchCl>(AlimtalkSearchCl.BUYER_NAME);
  const [searchValue, setSearchValue] = useState<string>('');
  const [serviceCode, setServiceCode] = useState<ServiceCode>(ServiceCode.ALL);
  const [alimCl, setAlimCl] = useState<AlimtalkAlimCl>(AlimtalkAlimCl.DEPOSIT_REQUEST);
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [sendType, setSendType] = useState<AlimtalkSendType>(AlimtalkSendType.ALL);
  const [sendCl, setSendCl] = useState<AlimTalkSendCl>(AlimTalkSendCl.ALL);

  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
  const { mutateAsync: extensionAlimtalkList } = useExtensionAlimtalkListMutation();
  const { mutateAsync: extensionAlimtalkDownloadExcel } = useExtensionAlimtalkDownloadExcelMutation();
  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('알림톡 결제통보');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const callList = (type?: string) => {
    let listParams: ExtensionAlimtalkListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      serviceCode: serviceCode,
      alimCl: alimCl,
      fromDate: fromDate,
      toDate: toDate,
      sendType: sendType,
      sendCl: sendCl,
      page: pageParam
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    extensionAlimtalkList(listParams).then((rs: ExtensionAlimtalkListResponse) => {
      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: ExtensionAlimtalkDownloadExcelParams = {
        mid: mid,
        searchCl: searchCl,
        searchValue: searchValue,
        serviceCode: serviceCode,
        alimCl: alimCl,
        fromDate: fromDate,
        toDate: toDate,
        sendType: sendType,
        sendCl: sendCl,
        //email: selectedEmail
      };
      extensionAlimtalkDownloadExcel(params).then((rs: ExtensionAlimtalkDownloadExcelResponse) => {
        console.log('Excel Download Status:', rs.status);
      });
    };
    setEmailBottomSheetOn(false);
  };

  const onClickToNavigate = () => {
    navigate(PATHS.additionalService.alimtalk.setting);
  };


  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const getAlimtalkList = () => {
    let rs = [];
    let date = '';
    let list = [];
    for (let i = 0; i < listItems.length; i++) {
      let item = listItems[i];
      if (!!item) {
        // sendDate format: "20211018140420" (YYYYMMDDHHmmss)
        let sendDate = item?.sendDate || '';
        let itemDate = sendDate.substring(0, 8);
        if (!!itemDate) {
          if (i === 0) {
            date = itemDate;
          }
          if (date !== itemDate) {
            if (list.length > 0) {
              rs.push(
                <ListDateGroup
                  additionalServiceCategory={AdditionalServiceCategory.Alimtalk}
                  mid={mid}
                  key={date + '-' + i}
                  date={date}
                  items={list as any}
                ></ListDateGroup>
              );
            }
            date = itemDate;
            list = [];
          }
          list.push(item);
        }
      }
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.Alimtalk}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list as any}
        ></ListDateGroup>
      );
    }
    return rs;
  }

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    serviceCode,
    alimCl,
    fromDate,
    toDate,
    sendType,
    sendCl
  ]);

  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="필터"
                    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="transaction-list">
              {getAlimtalkList()}
            </section>
            <div ref={ setTarget }></div>
          </div>
        </div>
      </main>
      <div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={() => onClickToNavigate()}
        >서비스 설정</button>
      </div>
      <AlimtalkFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        fromDate={fromDate}
        toDate={toDate}
        serviceCode={serviceCode}
        alimCl={alimCl}
        sendType={sendType}
        sendCl={sendCl}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setServiceCode={setServiceCode}
        setAlimCl={setAlimCl}
        setSendType={setSendType}
        setSendCl={setSendCl}
      ></AlimtalkFilter>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      >
      </EmailBottomSheet>
    </>
  );
};