import moment from 'moment';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { JSX, useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { ListDateGroup } from '../list-date-group';
import { AdditionalServiceCategory } from '../../model/types';
import { ExtensionFundAccountResultExcelParams, ExtensionFundAccountResultExcelResponse, ExtensionFundAccountResultListParams, ExtensionFundAccountResultListResponse, ExtensionFundAccountResultSummaryParams, ExtensionFundAccountResultSummaryResponse, FundAccountResultContent, FundAccountResultContentItem, FundAccountResultStatus, FundAccountSearchCl, FundAccountSearchDateType, FundAccountStatus } from '../../model/fund-account/types';
import { useExtensionFundAccountResultSummaryMutation } from '../../api/fund-account/use-extension-fund-account-result-summary-mutation';
import { useExtensionFundAccountResultExcelMutation } from '../../api/fund-account/use-extension-fund-account-result-excel-mutation';
import { useExtensionFundAccountResultListMutation } from '../../api/fund-account/use-extension-fund-account-result-list-mutation';
import { PATHS } from '@/shared/constants/paths';
import { NumericFormat } from 'react-number-format';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { FundAccountResultStatusBtnGroup, FundAccountStatusBtnGroup } from '../../model/fund-account/constant';
import { FundAccountResultFilter } from '../filter/fund-account-result-filter';
import { useStore } from '@/shared/model/store';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';

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

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

  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<FundAccountResultContentItem>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);

  const [mid, setMid] = useState<string>(userMid);
  const [searchCl, setSearchCl] = useState<FundAccountSearchCl>(FundAccountSearchCl.ACCOUNT_NAME);
  const [searchValue, setSearchValue] = useState<string>('');
  const [searchDateType, setSearchDateType] = useState<FundAccountSearchDateType>(FundAccountSearchDateType.REQUEST_DATE)
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [bankCode, setBankCode] = useState<string>('');
  const [resultStatus, setResultStatus] = useState<FundAccountResultStatus>(FundAccountResultStatus.ALL);

  const [email, setEmail] = useState<string>('');

  const [totalRequestCount, setTotalRequestCount] = useState<number>(0);
  const [totalRequestAmount, setTotalRequestAmount] = useState<number>(0);
  const [totalSuccessCount, setTotalSuccessCount] = useState<number>(0);
  const [totalSuccessAmount, setTotalSuccessAmount] = useState<number>(0);
  const [totalFailCount, setTotalFailCount] = useState<number>(0);
  const [totalFailAmount, setTotalFailAmount] = useState<number>(0);


  const { mutateAsync: extensionFundAccountResultList } = useExtensionFundAccountResultListMutation();
  const { mutateAsync: extensionFundAccountResultExcel } = useExtensionFundAccountResultExcelMutation();
  const { mutateAsync: extensionFundAccountResultSummary } = useExtensionFundAccountResultSummaryMutation();

  const callList = (option?: {
    sortType?: SortTypeKeys,
    resultStatus?: FundAccountResultStatus
  }) => {
    let listSummaryParams: ExtensionFundAccountResultListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      searchDateType: searchDateType,
      fromDate: fromDate,
      toDate: toDate,
      bankCode: bankCode,
      resultStatus: option?.resultStatus ?? resultStatus,
      page: pageParam
    };

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

    extensionFundAccountResultList(listSummaryParams).then((rs: any) => {
      console.log(rs);
      setListItems(rs.content);
    });
  };


  const callDownloadExcel = () => {
    let params: ExtensionFundAccountResultExcelParams = {
      mid: mid,
      email: email,
      searchDateType: searchDateType,
      fromDate: fromDate,
      toDate: toDate,
    };
    extensionFundAccountResultExcel(params).then((rs: ExtensionFundAccountResultExcelResponse) => {

    });
  };
  const callSummary = () => {
    let params: ExtensionFundAccountResultSummaryParams = {
      mid: mid
    };

    extensionFundAccountResultSummary(params).then((rs: ExtensionFundAccountResultSummaryResponse) => {
      setTotalRequestCount(rs.totalRequestCount);
      setTotalRequestAmount(rs.totalRequestAmount);
      setTotalSuccessCount(rs.totalSuccessCount);
      setTotalSuccessAmount(rs.totalSuccessAmount);
      setTotalFailCount(rs.totalFailCount);
      setTotalFailAmount(rs.totalFailAmount);
    });
  };

  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };

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

  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
    callList({
      sortType: sort
    });
  };
  const onClickToStatus = (val: FundAccountResultStatus) => {
    setResultStatus(val);
    callList({
      resultStatus: val
    });
  };

  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list = [];
    for (let i = 0; i < listItems.length; i++) {
      let items = listItems[i];
      if (!!items) {
        let requestDate = items?.requestDate;
        requestDate = requestDate?.substring(0, 8);
        if (!!requestDate) {
          if (i === 0) {
            date = requestDate;
          }
          if (date !== requestDate) {
            date = requestDate;
            if (list.length > 0) {
              rs.push(
                <ListDateGroup
                  additionalServiceCategory={AdditionalServiceCategory.FundAccountResult}
                  key={date + '-' + i}
                  date={date}
                  items={list}
                ></ListDateGroup>
              );
            }
            list = [];
          }
          list.push(items);
        }
      }
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.FundAccountResult}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list}
        ></ListDateGroup>
      );
    }
    return rs;
  };

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

  useEffect(() => {
    callList();
  }, [
    mid,
    searchCl,
    searchValue,
    searchDateType,
    fromDate,
    toDate,
    bankCode,
    resultStatus
  ]);

  const onClickToNavigate = () => {
    navigate(PATHS.additionalService.fundAccount.transferRequest);
  };


  return (
    <>
      <section className="summary-section pt-30">
        <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="필터"
              onClick={() => onClickToOpenFilter()}
            >
              <img
                src={IMAGE_ROOT + '/ico_setting.svg'}
                alt="검색옵션"
              />
            </button>
          </div>
          <button
            className="download-btn"
            aria-label="다운로드"
            onClick={() => onClickToDownloadExcel()}
          >
            <img
              src={IMAGE_ROOT + '/ico_download.svg'}
              alt="다운로드"
            />
          </button>
        </div>
        <div className="summary-extend">
          <ul className="summary-amount-list">
            <li className="summary-amount-item">
              <span className="label">요청</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalRequestAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={totalRequestCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">성공</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalSuccessAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={totalSuccessCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">실패</span>
              <span className="value">
                <span>
                  <NumericFormat
                    value={totalFailAmount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span className="unit"> 원 (</span>
                <span>
                  <NumericFormat
                    value={totalFailCount}
                    thousandSeparator
                    displayType="text"
                  ></NumericFormat>
                </span>
                <span>건)</span>
              </span>
            </li>
          </ul>
        </div>
      </section>

      <section className="filter-section">
        <SortTypeBox
          sortType={sortType}
          onClickToSort={onClickToSort}
        ></SortTypeBox>
        <div className="excrow mr-0">
          <div className="full-menu-keywords no-padding">
            {
              FundAccountResultStatusBtnGroup.map((value, index) => (
                <span
                  key={`key-service-code=${index}`}
                  className={`keyword-tag ${(resultStatus === value.value) ? 'active' : ''}`}
                  onClick={() => onClickToStatus(value.value)}
                >{value.name}</span>
              ))
            }
          </div>
        </div>
      </section>

      <section className="transaction-list">
        {getListDateGroup()}
      </section>
      <div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={onClickToNavigate}
        >이체 등록</button>
      </div>
      <FundAccountResultFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        searchDateType={searchDateType}
        fromDate={fromDate}
        toDate={toDate}
        bankCode={bankCode}
        resultStatus={resultStatus}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setSearchDateType={setSearchDateType}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setBankCode={setBankCode}
        setResultStatus={setResultStatus}
      ></FundAccountResultFilter>
    </>
  );
};