import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useTranslation } from 'react-i18next';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useLocation } from 'react-router';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import {
  ExtensionFundAccountDownloadReceiptParams,
  ExtensionFundAccountDownloadReceiptResponse,
  ExtensionFundAccountResultDetailParams,
  ExtensionFundAccountResultDetailResponse,
} from '@/entities/additional-service/model/fund-account/types';
import moment from 'moment';
import { useExtensionFundAccountResultDetailMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-result-detail-mutation';
import { useExtensionFundAccountDownloadReceiptMutation } from '@/entities/additional-service/api/fund-account/use-extension-fund-account-download-certificate-mutation';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';

export const FundAccountResultDetailPage = () => {
  const { t, i18n } = useTranslation();
  const { navigate } = useNavigate();
  const location = useLocation();

  const tid = location.state.tid;
  const mid = location.state.mid;

  const [detail, setDetail] = useState<ExtensionFundAccountResultDetailResponse>();
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const { mutateAsync: extensionFundAccountResultDetail } = useExtensionFundAccountResultDetailMutation();
  const { mutateAsync: extensionFundAccountDownlaodReceipt } = useExtensionFundAccountDownloadReceiptMutation();

  const callDetail = () => {
    let params: ExtensionFundAccountResultDetailParams = {
      mid: mid,
      tid: tid,
    };

    extensionFundAccountResultDetail(params).then((rs: ExtensionFundAccountResultDetailResponse) => {
      console.log(rs.requestDate)
      setDetail(rs);
    });
  };

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

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      let params: ExtensionFundAccountDownloadReceiptParams = {
        mid: mid,
        tid: tid,
        email: selectedEmail
      };
      extensionFundAccountDownlaodReceipt(params).then((rs: ExtensionFundAccountDownloadReceiptResponse) => {
        console.log('Receipt Download Status:', rs);
      });
    }
    setEmailBottomSheetOn(false);
  };

  useSetHeaderTitle('자금이체 상세');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.additionalService.fundAccount.resultList);
  });

  useEffect(() => {
    callDetail();
    console.log(detail?.requestDate)
  }, []);

  return (
    <>
      <main className="full-height">
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="pay-top">
              <div className="num-amount">
                <span className="amount">
                  <NumericFormat
                    value={detail?.amount}
                    thousandSeparator
                    displayType="text"
                    prefix={i18n.language === 'en' ? t('home.currencySymbol') : ''}
                    suffix={i18n.language === 'en' ? '' : t('home.currencyWon')}
                  ></NumericFormat>
                </span>
              </div>
              <div className="num-store">{detail?.accountName}({detail?.accountNo})</div>
              {detail?.applicationDate && (
                <div className="num-day">  {moment(detail?.applicationDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD HH:mm:ss')}</div>
              )}
            </div>
            {/* ✅ resultMessage가 "정상"일 때만 표시 */}
            {detail?.resultMessage === '정상' && (
              <div className="receipt-row">
                <button
                  type="button"
                  className="receipt-btn"
                  onClick={ onClickToOpenEmailBottomSheet }
                  >
                  <span className="icon-24 download"></span>
                  <span>입금확인서</span>
                </button>
              </div>
            )}
            <div className="detail-divider"></div>
            <div className="pay-detail">
              <div className="detail-title">상세 정보</div>
              <ul className="kv-list">
                <li className="kv-row">
                  <span className="k">요청일시</span>
                  <span className="v">{moment(detail?.requestDate,'YYYYMMDDHHmmss').format('YYYY.MM.DD HH:mm:ss')}</span>
                </li>
                <li className="kv-row">
                  <span className="k">이체일시</span>
                  <span className="v">{detail?.applicationDate ? moment(detail?.applicationDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD  HH:mm:ss') : '-'}</span>
                </li>
                <li className="kv-row">
                  <span className="k">이체결과</span>
                  <span className="v">{detail?.resultMessage || '-'}</span>
                </li>
                <li className="kv-row">
                  <span className="k">실패사유</span>
                  <span className="v">{detail?.failReason || '-'}</span>
                </li>
                <li className="kv-row">
                  <span className="k">수취인명</span>
                  <span className="v">{detail?.accountName}</span>
                </li>
                <li className="kv-row">
                  <span className="k">은행</span>
                  <span className="v">{detail?.bankName}</span>
                </li>
                <li className="kv-row">
                  <span className="k">계좌번호</span>
                  <span className="v">{detail?.accountNo}</span>
                </li>
                <li className="kv-row">
                  <span className="k">MID</span>
                  <span className="v">{mid}</span>
                </li>
                <li className="kv-row">
                  <span className="k">주문번호</span>
                  <span className="v">{detail?.moid}</span>
                </li>
                <li className="kv-row">
                  <span className="k">TID</span>
                  <span className="v">{detail?.tid}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </main>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};