import moment from 'moment';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { SortByKeys, AuthAndTransferStatus, AccountHolderAuthListItem } from '@/entities/additional-service/model/types';
import { useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { SortOptionsBox } from '@/entities/additional-service/ui/sort-options-box';

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 { authStatusBtnGroup } from '@/entities/additional-service/model/account-holder-auth/constant';
import { AccountHolderAuthList } from '@/entities/additional-service/ui/account-holder-auth/account-holder-auth-list';
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';

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

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest001m');
  const [fromDate, setFromDate] = useState(moment().format('YYYY-MM-DD'));
  const [toDate, setToDate] = useState(moment().format('YYYY-MM-DD'));
  const [authStatus, setAuthStatus] = useState<AuthAndTransferStatus>(AuthAndTransferStatus.ALL)

  useSetHeaderTitle('계좌점유인증');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(true);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: accountHolderAuthList } = useExtensionAccountHolderAuthListMutation();
  const { mutateAsync: downloadExcel } = useExtensionAccountHolderAuthDownloadExcelMutation();
  const callList = (option?: {
    sortBy?: string,
    val?: string
  }) => {
    pageParam.sortBy = (option?.sortBy) ? option.sortBy : sortBy;
    setPageParam(pageParam);
    let listParams = {
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      authStatus: authStatus,
      page: pageParam
    }

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

  const assembleData = (content: Array<AccountHolderAuthListItem>) => {
    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 onClickToDownloadExcel = () => {
    downloadExcel({
      mid: mid,
      fromDate: fromDate,
      toDate: toDate,
      authStatus: authStatus
    }).then((rs) => {
      console.log('Excel Downlaod Status : ' + rs.status)
    });
  }

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

  const onClickToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callList({ sortBy: sort })
  };


  const onClickToAuthStatus = (val: AuthAndTransferStatus) => {
    setAuthStatus(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(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"
                >
                  <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">
                  {
                    authStatusBtnGroup.map((value, index) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(authStatus === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToAuthStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </div>
            <AccountHolderAuthList
              listItems={listItems}
              mid={mid}
            ></AccountHolderAuthList>
          </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>
    </>
  );
};