import { motion } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { useEffect, useState } from 'react';
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';
import { DetailMotionDuration, DetailMotionStyle, DetailMotionVariants } from '@/entities/common/model/constant';
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';
import { showAlert } from '@/widgets/show-alert';

export interface FundAccountResultDetailProps {
  detailOn: boolean;
  setDetailOn: (detailOn: boolean) => void;
  mid: string;
  tid: string;
};
export const FundAccountResultDetail = ({
  detailOn,
  setDetailOn,
  mid,
  tid
}: FundAccountResultDetailProps) => {
  const { t } = useTranslation();

  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);
    }).catch((e: any) => {
      if (e.response?.data?.error?.message) {
        showAlert(e.response?.data?.error?.message);
        return;
      }
    });
  };

  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);
      }).catch((e: any) => {
        if(e.response?.data?.error?.message){
          showAlert(e.response?.data?.error?.message);
          return;
        }
      });
    }
    setEmailBottomSheetOn(false);
  };

  const onClickToClose = () => {
    setDetailOn(false);
  };

  useEffect(() => {
    if (!!mid && !!tid) {
      callDetail();
    }
  }, [mid, tid]);

  return (
    <>
      <motion.div
        className="full-menu-modal"
        initial="hidden"
        animate={(detailOn) ? 'visible' : 'hidden'}
        variants={DetailMotionVariants}
        transition={DetailMotionDuration}
        style={DetailMotionStyle}
      >
        <div className="full-menu-container pdw-16">
          <div className="full-menu-header">
            <div className="full-menu-title center">{t('additionalService.fundAccount.transferDetailTitle')}</div>
            <div className="full-menu-actions">
              <FullMenuClose
                addClass="full-menu-close"
                onClickToCallback={onClickToClose}
              ></FullMenuClose>
            </div>
          </div>
          <div className="pay-top">
            <div className="num-amount">
              <span className="amount">
                {t('home.money', { value: new Intl.NumberFormat('en-US').format(detail?.amount || 0) })}
              </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>{t('additionalService.fundAccount.depositCertificate')}</span>
              </button>
            </div>
          )}
          <div className="detail-divider"></div>
          <div className="pay-detail">
            <div className="detail-title">{t('additionalService.fundAccount.detailInfo')}</div>
            <ul className="kv-list">
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.requestDateTime')}</span>
                <span className="v">{moment(detail?.requestDate, 'YYYYMMDDHHmmss').format('YYYY.MM.DD HH:mm:ss')}</span>
              </li>
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.transferDateTime')}</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">{t('additionalService.fundAccount.transferResult')}</span>
                <span className="v">{detail?.resultMessage || '-'}</span>
              </li>
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.failureReason')}</span>
                <span className="v">{detail?.failReason || '-'}</span>
              </li>
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.beneficiaryName')}</span>
                <span className="v">{detail?.accountName}</span>
              </li>
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.bank')}</span>
                <span className="v">{detail?.bankName}</span>
              </li>
              <li className="kv-row">
                <span className="k">{t('additionalService.fundAccount.accountNumber')}</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">{t('transaction.fields.orderNumber')}</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>
      </motion.div>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};