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';
import { snackBar } from '@/shared/lib';

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,
      sendMessage: smsDetailData.sendMessage
    }).then((rs) => {
      if (rs.status) {
        snackBar("SMS 발송을 성공하였습니다.")
      } else {
        snackBar(`[실패] ${rs.error?.message}`)
      }
      setBottomSmsPaymentDetailResendOn(false);
    }).catch((error) => {
      snackBar(`[실패] ${error?.response?.data?.message || error?.response?.data?.error?.message}` || '[실패] 신청을 실패하였습니다.')
    });
  }

  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>
    </>
  );
};