// src/components/payment/modal/CardModal.tsx
import React, { useState } from 'react'
import { Box, Typography, CircularProgress } from '@mui/material'
import { useForm } from 'react-hook-form'

// ** Components
import BasePaymentModal from '../BasePaymentModal'
import CardPayment from 'src/views/components/card-payment'

interface CardModalProps {
  open: boolean
  onClose: () => void
  onConfirm: (data: Record<string, any>) => void
  totalAmount: number
}

interface PaymentFormValues {
  cardNumber: string
  nameOnCard: string
  expiryDate: string // expected format: MM/YY or MM/YYYY
  cvv: string
  issuingBank: string
  cardType: string
  modeOfPayment: string
}

const CardModal: React.FC<CardModalProps> = ({ open, onClose, onConfirm, totalAmount }) => {
  const [submitting, setSubmitting] = useState(false)

  const {
    control,
    handleSubmit,
    setValue,
    watch,
    clearErrors,
    reset,
    formState: { errors }
  } = useForm<PaymentFormValues>({
    defaultValues: {
      cardNumber: '',
      nameOnCard: '',
      expiryDate: '',
      cvv: '',
      issuingBank: '',
      cardType: '',
      modeOfPayment: 'CREDIT_CARD'
    }
  })

  // Split "MM/YY" or "MM/YYYY" into separate month/year values expected by the payment API
  const parseExpiry = (expiryDate: string) => {
    const parts = expiryDate.split('/').map(p => p.trim())
    const month = parts[0] || ''
    let year = parts[1] || ''

    // Normalize 2-digit year to 4-digit (e.g. "26" -> "2026")
    if (year.length === 2) {
      year = `20${year}`
    }

    return { month, year }
  }

  const onSubmit = (data: PaymentFormValues) => {
    const { month, year } = parseExpiry(data.expiryDate)

    // Remove all spaces from card number before sending to API
    const cleanCardNumber = data.cardNumber.replace(/\s/g, '')

    // Field names match the payment API's expected `payment.*` keys
    const paymentData = {
      cardNumber: cleanCardNumber,  // Send without spaces
      cardType: data.cardType,
      cardExpiryMonth: month,
      cardExpiryYear: year,
      cardCvv: data.cvv,
      nameOnCard: data.nameOnCard
    }

    onConfirm(paymentData)
  }

  // BasePaymentModal's "Confirm" button calls this directly (it's a plain
  // onClick handler, not a form submit button), so we trigger react-hook-form's
  // validation + submit manually here.
  const handleConfirmClick = async () => {
    setSubmitting(true)
    try {
      await handleSubmit(onSubmit)()
    } finally {
      setSubmitting(false)
    }
  }

  const handleClose = () => {
    reset()
    onClose()
  }

  return (
    <BasePaymentModal
      open={open}
      title='Card Payment'
      onClose={handleClose}
      onConfirm={handleConfirmClick}
    >
      <Typography variant='subtitle1' sx={{ mb: 2, fontWeight: 'bold' }}>
        Amount to charge: ₹{totalAmount.toFixed(2)}
      </Typography>

      <Box component='form' onSubmit={handleSubmit(onSubmit)}>
        <CardPayment control={control} watch={watch} setValue={setValue} clearErrors={clearErrors} errors={errors} />
      </Box>

      {submitting && (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
          <CircularProgress size={20} />
        </Box>
      )}
    </BasePaymentModal>
  )
}

export default CardModal