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 { HeaderType } from '@/entities/common/model/types';
import { AccountHolderSearchFilter } from '@/entities/additional-service/ui/account-holder-search/filter/account-holder-search-filter';
import { ProcessResult, AccountHolderSearchType, SortByKeys, AccountHolderSearchListItem } 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 { SortOptionsBox } from '@/entities/additional-service/ui/sort-options-box';
import { AccountHolderSearchList } from '@/entities/additional-service/ui/account-holder-search/account-holder-search-list';

const resultStatusBtnGroup = [
  { name: '전체', value: ProcessResult.ALL },
  { name: '성공', value: ProcessResult.SUCCESS },
  { name: '실패', value: ProcessResult.FAIL },
]

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

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState({});
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [mid, setMid] = useState<string>('nictest001m');
  const [searchType, setSearchType] = useState<AccountHolderSearchType>(AccountHolderSearchType.ACCOUNT_NO)
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [startDate, setStartDate] = useState(moment().format('YYYY-MM-DD'));
  const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));
  const [bank, setBank] = useState<string>('');
  const [processResult, setProcessResult] = useState<ProcessResult>(ProcessResult.ALL);

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

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

  const callList = (option?: {
    sortBy?: string,
    val?: string
  }) => {
    pageParam.sortBy = (option?.sortBy) ? option.sortBy : sortBy;
    setPageParam(pageParam);
    let listParams = {
      mid: mid,
      searchCl: searchType,
      searchValue: searchKeyword,
      fromDate: startDate,
      toDate: endDate,
      bankCode: bank,
      resultStatus: processResult,
      page: pageParam
    }

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

  const assembleData = (content: Array<AccountHolderSearchListItem>) => {
    console.log('rs.content:', content)
    let data: any = {};
    if (content && content.length > 0) {
      for (let i = 0; i < content?.length; i++) {
        let requestDate = content[i]?.requestDate?.substring(0, 8);
        let groupDate = moment(requestDate).format('YYYYMMDD');
        if (!!groupDate && !data.hasOwnProperty(groupDate)) {
          data[groupDate] = [];
        }
        if (!!groupDate && data.hasOwnProperty(groupDate)) {
          data[groupDate].push(content[i]);
        }
      }
    }
    console.log('Data : ', data)
    return data;
  };

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

  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: SortByKeys) => {
    setSortBy(sort);
    callList({ sortBy: sort })
  };

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

  useEffect(() => {
    callList();
  }, []);

  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"
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                    onClick={() => onClickToDownloadExcel()}
                  />
                </button>
              </div>
            </section>

            <div className="filter-section">
              <SortOptionsBox
                sortBy={sortBy}
                onClickToSort={onClickToSort}
              ></SortOptionsBox>
              <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>
    </>
  );
};