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 { 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, AccountHolderSearchType } from '@/entities/additional-service/model/account-holder-search/types';
import { resultStatusBtnGroup } from '@/entities/additional-service/model/account-holder-search/constant';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';

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

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

  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 [searchType, setSearchType] = useState<AccountHolderSearchType>(AccountHolderSearchType.ACCOUNT_NAME)
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [startDate, setStartDate] = useState(moment().format('YYYYMMDD'));
  const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
  const [bank, setBank] = useState<string>('');
  const [processResult, setProcessResult] = useState<ProcessResult>(ProcessResult.ALL);
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
  const [email, setEmail] = useState<string>('');

  useSetHeaderTitle('계좌성명조회');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: accountHolderSearchList } = useExtensionAccountHolderSearchListMutation();
  const { mutateAsync: downloadExcel } = useExtensionAccountHolderSearchDownloadExcelMutation();

  const callList = (option?: {
    sortType?: SortTypeKeys,
    processResult?: ProcessResult
  }) => {
    let listParams = {
      mid: mid,
      searchCl: searchType,
      searchValue: searchKeyword,
      fromDate: startDate,
      toDate: endDate,
      bankCode: bank,
      resultStatus: option?.processResult ?? processResult,
      page: pageParam
    }

    if (listParams.page) {
      listParams.page.sortType = option?.sortType || sortType;
      setPageParam(listParams.page);
    }

    accountHolderSearchList(listParams).then((rs) => {
      setListItems(rs.content);
    });
  }

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

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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {

      // 이메일을 설정한 후 다운로드 실행
      downloadExcel({
        mid: mid,
        //email: selectedEmail,
        searchCl: searchType,
        searchValue: searchKeyword,
        fromDate: startDate,
        toDate: endDate,
        bankCode: bank,
        resultStatus: processResult
      }).then((rs) => {
        console.log('Excel Download Status: ' + rs.status);
      });
    }
    setEmailBottomSheetOn(false);
  };

  const onClickToDownloadExcel = () => {
    downloadExcel({
      mid: mid,
      searchCl: searchType,
      searchValue: searchKeyword,
      fromDate: startDate,
      toDate: endDate,
      bankCode: bank,
      resultStatus: processResult
    }).then((rs) => {
      console.log('Excel Dowload Status : ' + rs.status);
    });
  };

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

  const onClickToTransactionStatus = (val: ProcessResult) => {
    setProcessResult(val);
    callList({
      processResult: val
    });
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    searchType,
    searchKeyword,
    startDate,
    endDate,
    bank,
    processResult
  ]);

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

            <div className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
              ></SortTypeBox>
              <div className="excrow">
                <div className="full-menu-keywords no-padding">
                  {
                    resultStatusBtnGroup.map((value, index) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(processResult === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToTransactionStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <AccountHolderSearchList
              listItems={listItems}
              mid={mid}
            ></AccountHolderSearchList>
          </div>
        </div>
      </main>
      <AccountHolderSearchFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchType={searchType}
        searchKeyword={searchKeyword}
        startDate={startDate}
        endDate={endDate}
        bank={bank}
        processResult={processResult}
        setMid={setMid}
        setSearchType={setSearchType}
        setSearchKeyword={setSearchKeyword}
        setStartDate={setStartDate}
        setEndDate={setEndDate}
        setBank={setBank}
        setProcessResult={setProcessResult}
      ></AccountHolderSearchFilter>

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