'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { useTranslations } from 'next-intl'
import { Mail, ArrowRight } from 'lucide-react'

interface ForgotPasswordFormProps {
  onSubmit?: (email: string) => void
}

export default function ForgotPasswordForm({ onSubmit }: ForgotPasswordFormProps) {
  const t = useTranslations('Auth.forgot')
  const tShared = useTranslations('Auth.shared')
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')
  const [submitted, setSubmitted] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!email) {
      setError(tShared('emailRequired'))
      return
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
      setError(tShared('emailInvalid'))
      return
    }
    setError('')

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

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

      onSubmit?.(email)
      setSubmitted(true)
    } catch {
      setError(tShared('networkError'))
    } finally {
      setIsSubmitting(false)
    }
  }

  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">
          <Mail size={28} className="text-green-600" />
        </div>
        <h3 className="text-lg font-semibold text-dark mb-2">{t('checkEmailTitle')}</h3>
        <p className="text-gray-custom text-sm mb-4">
          {t.rich('checkEmailBody', {
            email,
            strong: (chunks) => <strong>{chunks}</strong>,
          })}
        </p>
        <button
          onClick={() => setSubmitted(false)}
          className="text-primary hover:underline text-sm"
        >
          {t('tryAnother')}
        </button>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="text-center mb-4">
        <p className="text-gray-custom text-sm">{t('intro')}</p>
      </div>

      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{tShared('emailLabel')}</label>
        <div className="relative">
          <Mail size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type="email"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value)
              setError('')
            }}
            className={`w-full pl-10 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              error
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
            placeholder="john@example.com"
          />
        </div>
        {error && <p className="text-red-500 text-xs mt-1">{error}</p>}
      </div>

      <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 flex items-center justify-center gap-2 hover:shadow-md transition-all disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {isSubmitting ? t('submitting') : t('submit')}
        {!isSubmitting && <ArrowRight size={18} />}
      </motion.button>
    </form>
  )
}
