'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { User, Mail, Phone, Home, Building } from 'lucide-react'

export interface CheckoutFormData {
  email: string
  shipping_full_name: string
  shipping_phone: string
  shipping_address_line1: string
  shipping_address_line2: string
  shipping_city: string
  shipping_state: string
  shipping_postal_code: string
  shipping_landmark: string
  customer_notes: string
}

interface CheckoutFormProps {
  isLoggedIn: boolean
  initialValues?: Partial<CheckoutFormData>
  onSubmit: (data: CheckoutFormData) => void
}

const EMPTY_FORM: CheckoutFormData = {
  email: '',
  shipping_full_name: '',
  shipping_phone: '',
  shipping_address_line1: '',
  shipping_address_line2: '',
  shipping_city: '',
  shipping_state: '',
  shipping_postal_code: '',
  shipping_landmark: '',
  customer_notes: '',
}

// `initialValues` arrives asynchronously (the parent fetches /auth/me after
// mount) — rather than an effect syncing them into state after the fact
// (which cascades a render and trips the "no setState in effect" rule),
// the parent remounts this component via a `key` change once the real
// values are known, so the lazy useState initializer below just picks them
// up fresh. See checkout/page.tsx's `key={meLoaded ? 'me' : 'anon'}`.
export default function CheckoutForm({ isLoggedIn, initialValues, onSubmit }: CheckoutFormProps) {
  const t = useTranslations('Checkout')
  const [formData, setFormData] = useState<CheckoutFormData>(() => ({ ...EMPTY_FORM, ...initialValues }))
  const [errors, setErrors] = useState<Partial<Record<keyof CheckoutFormData, string>>>({})

  const setField = (field: keyof CheckoutFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
  }

  const validate = (): boolean => {
    const newErrors: Partial<Record<keyof CheckoutFormData, string>> = {}

    if (!isLoggedIn) {
      if (!formData.email) newErrors.email = t('emailRequired')
      else if (!/\S+@\S+\.\S+/.test(formData.email)) newErrors.email = t('emailInvalid')
    }
    if (formData.shipping_full_name.trim().length < 2) newErrors.shipping_full_name = t('fullNameRequired')
    if (!/^03[0-9]{9}$/.test(formData.shipping_phone)) newErrors.shipping_phone = t('phoneInvalid')
    if (formData.shipping_address_line1.trim().length < 3) newErrors.shipping_address_line1 = t('addressRequired')
    if (formData.shipping_city.trim().length < 2) newErrors.shipping_city = t('cityRequired')

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (validate()) onSubmit(formData)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('fullName')} *</label>
          <div className="relative">
            <User size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-custom" />
            <input
              type="text"
              value={formData.shipping_full_name}
              onChange={(e) => setField('shipping_full_name', e.target.value)}
              className={`w-full pl-10 pr-4 py-2.5 border rounded-lg focus:ring-1 focus:ring-primary outline-none ${errors.shipping_full_name ? 'border-red-400' : 'border-gray-200 focus:border-primary'}`}
              placeholder="John Doe"
            />
          </div>
          {errors.shipping_full_name && <p className="text-xs text-red-500 mt-1">{errors.shipping_full_name}</p>}
        </div>

        {!isLoggedIn && (
          <div>
            <label className="block text-dark font-medium mb-2 text-sm">{t('email')} *</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={formData.email}
                onChange={(e) => setField('email', e.target.value)}
                className={`w-full pl-10 pr-4 py-2.5 border rounded-lg focus:ring-1 focus:ring-primary outline-none ${errors.email ? 'border-red-400' : 'border-gray-200 focus:border-primary'}`}
                placeholder="john@example.com"
              />
            </div>
            {errors.email ? (
              <p className="text-xs text-red-500 mt-1">{errors.email}</p>
            ) : (
              <p className="text-xs text-gray-custom mt-1">{t('emailHelp')}</p>
            )}
          </div>
        )}
      </div>

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

      <div>
        <label className="block text-dark font-medium mb-2 text-sm flex items-center gap-2">
          <Home size={16} className="text-primary" />
          {t('address')} *
        </label>
        <input
          type="text"
          value={formData.shipping_address_line1}
          onChange={(e) => setField('shipping_address_line1', e.target.value)}
          className={`w-full px-4 py-2.5 border rounded-lg focus:ring-1 focus:ring-primary outline-none ${errors.shipping_address_line1 ? 'border-red-400' : 'border-gray-200 focus:border-primary'}`}
          placeholder="House #, Street #, Area"
        />
        {errors.shipping_address_line1 && <p className="text-xs text-red-500 mt-1">{errors.shipping_address_line1}</p>}
        <input
          type="text"
          value={formData.shipping_address_line2}
          onChange={(e) => setField('shipping_address_line2', e.target.value)}
          className="w-full mt-2 px-4 py-2.5 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none"
          placeholder={t('addressLine2')}
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('city')} *</label>
          <input
            type="text"
            value={formData.shipping_city}
            onChange={(e) => setField('shipping_city', e.target.value)}
            className={`w-full px-4 py-2.5 border rounded-lg focus:ring-1 focus:ring-primary outline-none ${errors.shipping_city ? 'border-red-400' : 'border-gray-200 focus:border-primary'}`}
            placeholder="Lahore"
          />
          {errors.shipping_city && <p className="text-xs text-red-500 mt-1">{errors.shipping_city}</p>}
        </div>

        <div>
          <label className="block text-dark font-medium mb-2 text-sm flex items-center gap-2">
            <Building size={16} className="text-primary" />
            {t('landmark')}
          </label>
          <input
            type="text"
            value={formData.shipping_landmark}
            onChange={(e) => setField('shipping_landmark', e.target.value)}
            className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none"
            placeholder={t('landmarkPlaceholder')}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('state')}</label>
          <input
            type="text"
            value={formData.shipping_state}
            onChange={(e) => setField('shipping_state', e.target.value)}
            className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none"
          />
        </div>
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('postalCode')}</label>
          <input
            type="text"
            value={formData.shipping_postal_code}
            onChange={(e) => setField('shipping_postal_code', e.target.value)}
            className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none"
          />
        </div>
      </div>

      <div>
        <label className="block text-dark font-medium mb-2 text-sm">{t('notes')}</label>
        <textarea
          value={formData.customer_notes}
          onChange={(e) => setField('customer_notes', e.target.value)}
          rows={3}
          className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none resize-none"
          placeholder={t('notesPlaceholder')}
        />
      </div>

      <button
        type="submit"
        className="w-full bg-gradient-primary text-white py-3 rounded-lg font-semibold hover:shadow-md transition cursor-pointer"
      >
        {t('continueToPayment')}
      </button>
    </form>
  )
}
