import moment from 'moment';
import { PATHS } from '@/shared/constants/paths';
import { useEffect, useState } from 'react';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { DefaultRequestPagination, HeaderType } from '@/entities/common/model/types';
import { AccountHolderSearchFilter } from '@/entities/additional-service/ui/account-holder-search/filter/account-holder-search-filter';
import { DetailData, ProcessResult } from '@/entities/additional-service/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useExtensionAccountHolderSearchListMutation } from '@/entities/additional-service/api/account-holder-search/use-extension-account-holder-search-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionAccountHolderSearchDownloadExcelMutation } from '@/entities/additional-service/api/account-holder-search/use-extension-account-holder-search-download-excel-mutation';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { SortTypeKeys } from '@/entities/common/model/types';
import { AccountHolderSearchList } from '@/entities/additional-service/ui/account-holder-search/account-holder-search-list';
import { useStore } from '@/shared/model/store';
import { AccountHolderSearchListItem, AccountHolderSearchCl, AccountHolderResultStatus } from '@/entities/additional-service/model/account-holder-search/types';
import { getResultStatusBtnGroup } from '@/entities/additional-service/model/account-holder-search/constant';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import { useTranslation } from 'react-i18next';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { snackBar } from '@/shared/lib';

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

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

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

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<AccountHolderSearchListItem>>([]);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [mid, setMid] = useState<string>(userMid);
  const [searchCl, setSearchCl] = useState<AccountHolderSearchCl>(AccountHolderSearchCl.ACCOUNT_NAME)
  const [searchValue, setSearchValue] = useState<string>('');
  const [startDate, setStartDate] = useState(moment().format('YYYYMMDD'));
  const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
  const [bank, setBank] = useState<string>('');
  const [resultStatus, setResultStatus] = useState<AccountHolderResultStatus>(AccountHolderResultStatus.ALL);
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
  const [detailOn, setDetailOn] = useState<boolean>(false);
  const [detailTid, setDetailTid] = useState<string>('');
  const [detailServiceCode, setDetailServiceCode] = useState<string>('');

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

  const { mutateAsync: accountHolderSearchList } = useExtensionAccountHolderSearchListMutation();
  const { mutateAsync: downloadExcel } = useExtensionAccountHolderSearchDownloadExcelMutation();
  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: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      fromDate: startDate,
      toDate: endDate,
      bankCode: bank,
      resultStatus: resultStatus,
      page: {
        ...pageParam,
        ...{ sortType: sortType }
      }
    }
    if (type !== 'page' && listParams.page) {
      listParams.page.cursor = null;
    }

    accountHolderSearchList(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 onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };

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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      downloadExcel({
        mid: mid,
        email: selectedEmail,
        searchCl: searchCl,
        searchValue: searchValue,
        fromDate: startDate,
        toDate: endDate,
        bankCode: bank,
        resultStatus: resultStatus
      }).then((rs) => {
        if (rs.status) {
          setTimeout(() => {
            snackBar("다운로드가 완료되었습니다.");
          }, 2000);
        } else {
          snackBar("다운로드에 실패했습니다.")
        }
      });
    }
    setEmailBottomSheetOn(false);
  };

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

  const onClickToTransactionStatus = (val: AccountHolderResultStatus) => {
    setResultStatus(val);
  };

  const setDetailDate = (detailData: DetailData) => {
    setDetailOn(detailData.detailOn);
    setDetailTid(detailData.tid);
    if(detailData?.serviceCode) {
      setDetailServiceCode(detailData?.serviceCode);
    }
  }

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    startDate,
    endDate,
    bank,
    resultStatus,
    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={t('filter.filter')}
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt={t('filter.searchOptions')}
                      onClick={() => onClickToOpenFilter()}
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  onClick={onClickToOpenEmailBottomSheet}
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt={t('filter.download')}
                  />
                </button>
              </div>
            </section>

            <div className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
                sortOptions={[
                  { key: SortTypeKeys.LATEST, label: t('common.latest') },
                  { key: SortTypeKeys.OLDEST, label: t('common.oldest') }
                ]}
              ></SortTypeBox>
              <div className="excrow">
                <div className="full-menu-keywords no-padding">
                  {
                    getResultStatusBtnGroup(t).map((value: any, index: number) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(resultStatus === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToTransactionStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <AccountHolderSearchList
              listItems={listItems}
              mid={mid}
            ></AccountHolderSearchList>
            <div ref={setTarget}></div>
          </div>
        </div>
      </main>
      <AccountHolderSearchFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchType={searchCl}
        searchKeyword={searchValue}
        startDate={startDate}
        endDate={endDate}
        bank={bank}
        resultStatus={resultStatus}
        setMid={setMid}
        setSearchType={setSearchCl}
        setSearchKeyword={setSearchValue}
        setStartDate={setStartDate}
        setEndDate={setEndDate}
        setBank={setBank}
        setResultStatus={setResultStatus}
      ></AccountHolderSearchFilter>

      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      />
    </>
  );
};