import moment from 'moment';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DefaultRequestPagination, HeaderType } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { SortTypeKeys } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useExtensionAccountHolderAuthListMutation } from '@/entities/additional-service/api/account-holder-auth/use-extension-account-holder-auth-list-mutation';
import { getAuthStatusBtnGroup } from '@/entities/additional-service/model/account-holder-auth/constant';
import { AccountHolderAuthList } from '@/entities/additional-service/ui/account-holder-auth/account-holder-auth-list';
import { useTranslation } from 'react-i18next';
import { useExtensionAccountHolderAuthDownloadExcelMutation } from '@/entities/additional-service/api/account-holder-auth/use-extension-account-holder-auth-download-excel-mutation';
import { AccountHolderAuthFilter } from '@/entities/additional-service/ui/account-holder-auth/filter/account-holder-auth-filter';
import { useStore } from '@/shared/model/store';
import { AccountHolderAuthListItem, AccountHolderAuthStatus, ExtensionAccountHolderAuthContentItem, ExtensionAccountHolderAuthDownloadExcelParams, ExtensionAccountHolderAuthDownloadExcelResponse } from '@/entities/additional-service/model/account-holder-auth/types';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
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 AccountHolderAuthPage = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();

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

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

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<ExtensionAccountHolderAuthContentItem>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [authStatus, setAuthStatus] = useState<AccountHolderAuthStatus>(AccountHolderAuthStatus.ALL)
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
  useSetHeaderTitle('계좌점유인증');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: accountHolderAuthList } = useExtensionAccountHolderAuthListMutation();
  const { mutateAsync: downloadExcel } = useExtensionAccountHolderAuthDownloadExcelMutation();
  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) => {
    let listParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      authStatus: authStatus,
      page: {
        ...pageParam,
        ...{ sortType: sortType }
      }
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    accountHolderAuthList(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 onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };

  const onClickToAuthStatus = (val: AccountHolderAuthStatus) => {
    setAuthStatus(val);
  };


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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      const params: ExtensionAccountHolderAuthDownloadExcelParams = { // 추후 수정필요
        mid: mid,
        email: selectedEmail,
        fromDate: fromDate,
        toDate: toDate,
        authStatus: authStatus
      };
      downloadExcel(params).then((rs: ExtensionAccountHolderAuthDownloadExcelResponse) => {
        console.log('Excel Download Status:', rs.status);
      });
    }
    setEmailBottomSheetOn(false);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    fromDate,
    toDate,
    authStatus,
    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(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="다운로드"
                  onClick={() => onClickToOpenEmailBottomSheet()}
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                  />
                </button>
              </div>
            </section>

            <div className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
                sortOptions={[
                  { key: SortTypeKeys.LATEST, label: '최신순' },
                  { key: SortTypeKeys.OLDEST, label: '오래된순' }
                ]}
              ></SortTypeBox>
              <div className="excrow">
                <div className="full-menu-keywords no-padding">
                  {
                    getAuthStatusBtnGroup(t).map((value: any, index: number) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(authStatus === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToAuthStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <AccountHolderAuthList
              additionalServiceCategory={AdditionalServiceCategory.AccountHolderAuth}
              listItems={listItems}
              mid={mid}
            ></AccountHolderAuthList>
            <div ref={ setTarget }></div>
          </div>
        </div>
      </main>
      <AccountHolderAuthFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        startDate={fromDate}
        endDate={toDate}
        authStatus={authStatus}
        setMid={setMid}
        setStartDate={setFromDate}
        setEndDate={setToDate}
        setAuthStatus={setAuthStatus}
      >
      </AccountHolderAuthFilter>

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