'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { useTranslations } from 'next-intl'
import { Lock, Eye, EyeOff, CheckCircle } from 'lucide-react'
import { useRouter } from 'next/navigation'

interface ResetPasswordFormProps {
  token?: string
  onSubmit?: (password: string) => void
}

export default function ResetPasswordForm({ token, onSubmit }: ResetPasswordFormProps) {
  const router = useRouter()
  const t = useTranslations('Auth.reset')
  const tShared = useTranslations('Auth.shared')
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: '',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitted, setSubmitted] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formError, setFormError] = useState('')

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
    if (errors[name]) {
      // Remove the error entirely instead of setting to undefined
      const newErrors = { ...errors }
      delete newErrors[name]
      setErrors(newErrors)
    }
  }

  const validate = () => {
    const newErrors: Record<string, string> = {}

    if (!formData.password) {
      newErrors.password = tShared('passwordRequired')
    } else if (formData.password.length < 6) {
      newErrors.password = tShared('passwordTooShort')
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = t('passwordMismatch')
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setFormError('')
    if (!validate()) return

    if (!token) {
      setFormError(t('missingToken'))
      return
    }

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

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

      onSubmit?.(formData.password)
      setSubmitted(true)

      // Redirect to login after 3 seconds
      setTimeout(() => {
        router.push('/login')
      }, 3000)
    } catch {
      setFormError(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">
          <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 mb-4">{t('successBody')}</p>
        <button
          onClick={() => router.push('/login')}
          className="text-primary hover:underline text-sm"
        >
          {t('goToLogin')}
        </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>

      {formError && (
        <p className="text-red-500 text-sm text-center bg-red-50 border border-red-200 rounded-lg px-4 py-3">{formError}</p>
      )}

      {/* New Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('newPasswordLabel')}</label>
        <div className="relative">
          <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type={showPassword ? 'text' : 'password'}
            name="password"
            value={formData.password}
            onChange={handleChange}
            className={`w-full pl-10 pr-12 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.password
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
            placeholder="••••••••"
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-custom hover:text-primary transition"
          >
            {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        </div>
        {errors.password && <p className="text-red-500 text-xs mt-1">{errors.password}</p>}
      </div>

      {/* Confirm Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('confirmPasswordLabel')}</label>
        <div className="relative">
          <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type={showConfirmPassword ? 'text' : 'password'}
            name="confirmPassword"
            value={formData.confirmPassword}
            onChange={handleChange}
            className={`w-full pl-10 pr-12 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.confirmPassword
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
            placeholder="••••••••"
          />
          <button
            type="button"
            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-custom hover:text-primary transition"
          >
            {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        </div>
        {errors.confirmPassword && <p className="text-red-500 text-xs mt-1">{errors.confirmPassword}</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')}
      </motion.button>
    </form>
  )
}
