import { motion } from 'framer-motion';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { SmsPaymentDetailResendProps } from '../../../additional-service/model/sms-payment/types';
import { useExtensionSmsResendMutation } from '../../api/sms-payment/use-extension-sms-resend-mutation';
import appBridge from '@/shared/lib/appBridge';

export const SmsPaymentDetailResend = ({
  bottomSmsPaymentDetailResendOn,
  setBottomSmsPaymentDetailResendOn,
  smsDetailData,
  mid,
  tid
}: SmsPaymentDetailResendProps) => {
  
  const variants = {
    hidden: { y: '100%' },
    visible: { y: '0%' },
  };

  const {mutateAsync : resendMessage } = useExtensionSmsResendMutation();

  const onClickResend = () => {
    // sendMessage가 없으면 재발송 불가
    if (!smsDetailData?.sendMessage) {
      return;
    }

    resendMessage({
      mid: mid,
      tid: tid
    }).then((rs) => {
      console.log("Resend 성공: ", rs);
      appBridge.showToast("SMS 발송을 성공하였습니다.");
      setBottomSmsPaymentDetailResendOn(false);
    }).catch((error) => {
      console.error("Resend 실패: ", error);

      // 실패 토스트 메시지 표시
      const errorMessage = error?.message || "알 수 없는 오류";
      const failMessage = `[실패] ${errorMessage}`;
      appBridge.showToast(failMessage);
    });
  }

  const onClickToClose = () => {
    // close
    setBottomSmsPaymentDetailResendOn(false);
  };

  return (
    <>
      { bottomSmsPaymentDetailResendOn &&
        <div className="bg-dim"></div>
      }
      <motion.div 
        className="bottomsheet"
        initial="hidden"
        animate={ (bottomSmsPaymentDetailResendOn)? 'visible': 'hidden' }
        variants={ variants }
        transition={{ duration: 0.5 }}
      >
        <div className="bottomsheet-header">
          <div className="bottomsheet-title">
            <h2>SMS 상세 & 재발송</h2>
            <button 
              className="close-btn" 
              type="button"
            >
              <img 
                src={ IMAGE_ROOT + '/ico_close.svg' }
                alt="닫기"
                onClick={ () => onClickToClose() }
              />
            </button>
          </div>
        </div>
        <div className="resend-info">
          <div className="resend-row">발신자(번호) : {smsDetailData?.senderName || '-'}({smsDetailData?.senderNumber || '-'})</div>
          <div className="resend-row">수신자(번호) : {smsDetailData?.receiverName || '-'}({smsDetailData?.receiverNumber || '-'})</div>
        </div>
        <div className="resend-box">
          <p className="resend-text">{smsDetailData?.sendMessage || '-'}</p>
        </div>
        <div className="bottomsheet-footer">
          <button
            className={`btn-50 flex-1 ${smsDetailData?.sendMessage ? 'btn-blue' : 'btn-gray'}`}
            type="button"
            onClick={onClickResend}
            disabled={!smsDetailData?.sendMessage}
          >
            신청
          </button>
        </div>
      </motion.div>
    </>
  );
};