'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useTranslations, useLocale } from 'next-intl'
import { User, Mail, Lock, Eye, EyeOff, Phone, AlertCircle } from 'lucide-react'
import { getGuestSessionId } from '@/lib/cart/guestSession'
import { useCartStore } from '@/store/cartStore'
import { useWishlistStore } from '@/store/wishlistStore'
import { getCapturedReferralCode, clearCapturedReferralCode } from '@/lib/referral/referralCapture'

interface RegisterFormProps {
  onSubmit?: (data: { name: string; email: string; phone: string; password: string }) => void
}

export default function RegisterForm({ onSubmit }: RegisterFormProps) {
  const router = useRouter()
  const locale = useLocale()
  const fetchCart = useCartStore((s) => s.fetchCart)
  const fetchWishlist = useWishlistStore((s) => s.fetchWishlist)
  const t = useTranslations('Auth.register')
  const tShared = useTranslations('Auth.shared')
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formError, setFormError] = useState('')
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})

  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.name) newErrors.name = t('nameRequired')
    else if (formData.name.length < 2) newErrors.name = t('nameTooShort')

    if (!formData.email) newErrors.email = tShared('emailRequired')
    else if (!/\S+@\S+\.\S+/.test(formData.email)) newErrors.email = tShared('emailInvalid')

    if (!formData.phone) newErrors.phone = t('phoneRequired')
    else if (!/^03[0-9]{9}$/.test(formData.phone)) newErrors.phone = t('phoneInvalid')

    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

    const submitData = {
      name: formData.name, email: formData.email, phone: formData.phone, password: formData.password,
      session_id: getGuestSessionId(), referral_code: getCapturedReferralCode() ?? undefined,
    }
    setIsSubmitting(true)
    try {
      const res = await fetch('/api/frontend/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(submitData),
      })
      const data = await res.json()

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

      onSubmit?.(submitData)
      clearCapturedReferralCode()
      // The server just merged the guest cart into this brand-new account's
      // cart (see mergeGuestCartIntoUser) — refetch so the header
      // badge/cart page reflect it instead of the pre-signup, guest-only
      // items still sitting in the store.
      fetchCart(locale)
      fetchWishlist(locale)
      router.push('/account')
      router.refresh()
    } catch {
      setFormError(tShared('networkError'))
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {formError && (
        <div className="flex items-center gap-2 bg-red-50 border border-red-200 text-red-600 text-sm rounded-lg px-4 py-3">
          <AlertCircle size={16} className="shrink-0" />
          <span>{formError}</span>
        </div>
      )}

      {/* Full Name */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('nameLabel')}</label>
        <div className="relative">
          <User size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
            className={`w-full pl-10 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.name
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
            placeholder={t('namePlaceholder')}
          />
        </div>
        {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name}</p>}
      </div>

      {/* Email */}
      <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"
            name="email"
            value={formData.email}
            onChange={handleChange}
            className={`w-full pl-10 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.email
                ? '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>
        {errors.email && <p className="text-red-500 text-xs mt-1">{errors.email}</p>}
      </div>

      {/* Phone Number */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('phoneLabel')}</label>
        <div className="relative">
          <Phone size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
          <input
            type="tel"
            name="phone"
            value={formData.phone}
            onChange={handleChange}
            className={`w-full pl-10 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-1 transition ${
              errors.phone
                ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                : 'border-gray-200 focus:border-primary focus:ring-primary'
            }`}
            placeholder={t('phonePlaceholder')}
          />
        </div>
        {errors.phone && <p className="text-red-500 text-xs mt-1">{errors.phone}</p>}
      </div>

      {/* Password */}
      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{tShared('passwordLabel')}</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>

      {/* Terms Agreement */}
      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          required
          className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
        />
        <span className="text-sm text-gray-custom">
          {t('agreeText')}{' '}
          <Link href="/terms" className="text-primary hover:underline">{t('termsLink')}</Link>
          {' '}{t('andText')}{' '}
          <Link href="/privacy" className="text-primary hover:underline">{t('privacyLink')}</Link>
        </span>
      </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 flex items-center justify-center gap-2 hover:shadow-md transition-all mt-6 disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {isSubmitting ? t('submitting') : t('submit')}
      </motion.button>
    </form>
  )
}
