'use client'

import { useState, useRef, useEffect } from 'react'
import * as motion from 'framer-motion/m'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { CheckCircle, RefreshCw } from 'lucide-react'

interface VerifyOTPFormProps {
  email?: string
  phone?: string
  onSubmit?: (otp: string) => void
  onResend?: () => void
}

export default function VerifyOTPForm({ email, phone, onSubmit, onResend }: VerifyOTPFormProps) {
  const router = useRouter()
  const t = useTranslations('Auth.verify')
  const tShared = useTranslations('Auth.shared')
  const [otp, setOtp] = useState(['', '', '', '', '', ''])
  const [error, setError] = useState('')
  const [submitted, setSubmitted] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [resendTimer, setResendTimer] = useState(30)
  const inputRefs = useRef<(HTMLInputElement | null)[]>([])

  useEffect(() => {
    if (resendTimer > 0) {
      const timer = setTimeout(() => setResendTimer(resendTimer - 1), 1000)
      return () => clearTimeout(timer)
    }
  }, [resendTimer])

  const handleChange = (index: number, value: string) => {
    if (value.length > 1) value = value[0]
    if (!/^\d*$/.test(value)) return

    const newOtp = [...otp]
    newOtp[index] = value
    setOtp(newOtp)
    setError('')

    // Auto-focus next input
    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus()
    }
  }

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      inputRefs.current[index - 1]?.focus()
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const otpValue = otp.join('')
    if (otpValue.length !== 6) {
      setError(t('enterCode'))
      return
    }
    if (!email) {
      setError(t('missingEmail'))
      return
    }
    setError('')

    setIsSubmitting(true)
    try {
      const res = await fetch('/api/frontend/auth/verify-email/confirm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ email, code: otpValue }),
      })
      const data = await res.json()

      if (!res.ok || !data.success) {
        setError(data.message || t('genericError'))
        return
      }

      onSubmit?.(otpValue)
      setSubmitted(true)
      setTimeout(() => {
        router.push('/account')
      }, 2000)
    } catch {
      setError(tShared('networkError'))
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleResend = async () => {
    if (resendTimer !== 0) return
    setResendTimer(30)
    onResend?.()
    try {
      await fetch('/api/frontend/auth/verify-email/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      })
    } catch {
      // Non-critical — the resend timer already restarted; the "verify
      // email" banner elsewhere offers another chance to resend.
    }
  }

  if (submitted) {
    return (
      <div className="text-center py-8">
        <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <CheckCircle size={28} className="text-green-600" />
        </div>
        <h3 className="text-lg font-semibold text-dark mb-2">{t('successTitle')}</h3>
        <p className="text-gray-custom text-sm">{t('successBody')}</p>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="text-center">
        <p className="text-gray-custom text-sm">{t('sentTo')}</p>
        <p className="text-dark font-medium mt-1">
          {email || phone || t('fallbackTarget')}
        </p>
      </div>

      {/* OTP Inputs */}
      <div className="flex justify-center gap-3">
        {otp.map((digit, index) => (
          <input
            key={index}
            ref={(el) => { inputRefs.current[index] = el }}
            type="text"
            inputMode="numeric"
            maxLength={1}
            value={digit}
            onChange={(e) => handleChange(index, e.target.value)}
            onKeyDown={(e) => handleKeyDown(index, e)}
            className={`w-12 h-12 text-center text-xl font-semibold border rounded-lg focus:outline-none focus:ring-2 transition ${
              error
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
          />
        ))}
      </div>

      {error && <p className="text-red-500 text-sm text-center">{error}</p>}

      {/* Resend */}
      <div className="text-center">
        <button
          type="button"
          onClick={handleResend}
          disabled={resendTimer > 0}
          className={`text-sm flex items-center justify-center gap-1 mx-auto ${
            resendTimer > 0
              ? 'text-gray-custom cursor-not-allowed'
              : 'text-primary hover:underline'
          }`}
        >
          <RefreshCw size={14} />
          {resendTimer > 0 ? t('resendIn', { seconds: resendTimer }) : t('resend')}
        </button>
      </div>

      {/* Submit Button */}
      <motion.button
        whileHover={{ scale: 1.02 }}
        whileTap={{ scale: 0.98 }}
        type="submit"
        disabled={isSubmitting}
        className="w-full bg-gradient-primary text-white py-3 rounded-lg font-semibold hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {isSubmitting ? t('submitting') : t('submit')}
      </motion.button>
    </form>
  )
}
