import moment from 'moment';
import { useEffect, useState } from 'react';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { SmsPaymentDetailResend } from '@/entities/additional-service/ui/sms-payment/sms-payment-detail-resend';
import { HeaderType, SortByKeys } from '@/entities/common/model/types';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { SmsPaymentListItem, SmsPaymentSearchType, SmsType, ExtensionSmsDetailResponse } from '@/entities/additional-service/model/sms-payment/types';
import { useExtensionSmsListMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-list-mutation';
import { useExtensionSmsDownloadExcelMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-download-excel-mutation';
import { SmsPaymentList } from '@/entities/additional-service/ui/sms-payment/sms-payment-list';
import { SmsPaymentFilter } from '@/entities/additional-service/ui/sms-payment/sms-payment-filter';
import { useExtensionSmsDetailMutation } from '@/entities/additional-service/api/sms-payment/use-extension-sms-detail-mutation';


export const SmsPaymentPage = () => {
  const { navigate } = useNavigate();
  const [bottomSmsPaymentDetailResendOn, setBottomSmsPaymentDetailResendOn] = useState<boolean>(false)

  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 [selectedTid, setSelectedTid] = useState<string>('');
  const [selectedMid, setSelectedMid] = useState<string>('');
  const [searchCl, setSearchCl] = useState<SmsPaymentSearchType>(SmsPaymentSearchType.BUYER_NAME)
  const [searchValue, setSearchValue] = useState<string>('')
  const [fromDate, setFromDate] = useState(moment().format('YYYY-MM-DD'));
  const [toDate, setToDate] = useState(moment().format('YYYY-MM-DD'));
  const [smsCl, setSmsCl] = useState<SmsType>(SmsType.ALL);
  const [smsDetailData, setSmsDetailData] = useState<ExtensionSmsDetailResponse | null>(null);

  const { mutateAsync: smsPaymentList } = useExtensionSmsListMutation();
  const { mutateAsync: downloadExcel } = useExtensionSmsDownloadExcelMutation();
  const { mutateAsync: detail } = useExtensionSmsDetailMutation();

  useSetHeaderTitle('SMS 결제 통보');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(true);

  const callList = (option?: {
    sortBy?: string,
    val?: string
  }) => {
    pageParam.sortBy = (option?.sortBy) ? option.sortBy : sortBy;
    setPageParam(pageParam);

    let listParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      fromDate: fromDate,
      toDate: toDate,
      smsCl: smsCl === SmsType.ALL ? '' : smsCl,
      page: pageParam
    }

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

  const assembleData = (content: Array<SmsPaymentListItem>) => {
    let data: any = {};
    if (content && content.length > 0) {
      for (let i = 0; i < content?.length; i++) {
        let paymentDate = content[i]?.paymentDate?.substring(0, 8);
        let groupDate = moment(paymentDate).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 callDetail = (selectedMid: string, selectedTid: string) => {
    console.log("Selected Mid: ", selectedMid, "Selected Tid: ", selectedTid)
    detail({
      mid: selectedMid,
      tid: selectedTid
    }).then((rs) => {
      console.log('Detail info : ', rs)
      setSmsDetailData(rs);
    })
  }

  const onClickToDownloadExcel = () => {
    downloadExcel({
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      fromDate: fromDate,
      toDate: toDate,
      smsCl: smsCl === SmsType.ALL ? '' : smsCl,
    }).then((rs) => {
      console.log('Excel Dowload Status : ' + rs.status)
    });
  }

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


  const onClickToShowDetail = (itemMid: string, itemTid: string) => {
    setSelectedMid(itemMid);
    setSelectedTid(itemTid);
    callDetail(itemMid, itemTid);
    setBottomSmsPaymentDetailResendOn(true);
  };

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <section className="summary-section no-border">
              <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="다운로드"
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                    onClick={() => onClickToDownloadExcel()}
                  />
                </button>
              </div>
            </section>
            <div className="detail-divider"></div>
            <SmsPaymentList
              listItems={listItems}
              mid={mid}
              onResendClick={onClickToShowDetail}
            ></SmsPaymentList>
          </div>
        </div>
      </main>

      <SmsPaymentDetailResend
        bottomSmsPaymentDetailResendOn={bottomSmsPaymentDetailResendOn}
        setBottomSmsPaymentDetailResendOn={setBottomSmsPaymentDetailResendOn}
        smsDetailData={smsDetailData}
        mid={selectedMid}
        tid={selectedTid}
      ></SmsPaymentDetailResend>

      <SmsPaymentFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchCl={searchCl}
        searchValue={searchValue}
        fromDate={fromDate}
        toDate={toDate}
        smsCl={smsCl}
        setMid={setMid}
        setSearchCl={setSearchCl}
        setSearchValue={setSearchValue}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setSmsCl={setSmsCl}
      ></SmsPaymentFilter>
    </>
  );
};