'use client'

import { useState } from 'react'
import { useRouter } from '@/i18n/navigation'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Save, X } from 'lucide-react'
import { getApiErrorMessage } from '@/lib/utils/apiError'

export interface AddressFormData {
  full_name: string
  phone: string
  alternate_phone: string
  address_line1: string
  address_line2: string
  city: string
  state: string
  postal_code: string
  address_type: 'home' | 'work' | 'other'
  landmark: string
  is_default: boolean
}

const EMPTY_FORM: AddressFormData = {
  full_name: '',
  phone: '',
  alternate_phone: '',
  address_line1: '',
  address_line2: '',
  city: '',
  state: '',
  postal_code: '',
  address_type: 'home',
  landmark: '',
  is_default: false,
}

interface AddressFormProps {
  addressId?: string
  initialData?: Partial<AddressFormData>
}

// Shared by both /account/addresses/add and /account/addresses/edit/[id] —
// `addressId` is the only thing that changes which real API call this makes
// (POST /api/frontend/addresses vs. PUT /api/frontend/addresses/[id]).
export default function AddressForm({ addressId, initialData }: AddressFormProps) {
  const isEditing = Boolean(addressId)
  const router = useRouter()
  const t = useTranslations('Account.addressForm')
  const [formData, setFormData] = useState<AddressFormData>({ ...EMPTY_FORM, ...initialData })
  const [errors, setErrors] = useState<Partial<Record<keyof AddressFormData, string>>>({})
  const [saving, setSaving] = useState(false)

  const setField = <K extends keyof AddressFormData>(field: K, value: AddressFormData[K]) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
  }

  const validate = (): boolean => {
    const newErrors: Partial<Record<keyof AddressFormData, string>> = {}
    if (formData.full_name.trim().length < 2) newErrors.full_name = t('fullNameRequired')
    if (!/^03[0-9]{9}$/.test(formData.phone)) newErrors.phone = t('phoneInvalid')
    if (formData.alternate_phone && !/^03[0-9]{9}$/.test(formData.alternate_phone)) newErrors.alternate_phone = t('phoneInvalid')
    if (formData.address_line1.trim().length < 3) newErrors.address_line1 = t('addressRequired')
    if (formData.city.trim().length < 2) newErrors.city = t('cityRequired')
    if (formData.state.trim().length < 2) newErrors.state = t('stateRequired')
    if (formData.postal_code.trim().length < 2) newErrors.postal_code = t('postalCodeRequired')
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

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

    setSaving(true)
    try {
      const res = await fetch(isEditing ? `/api/frontend/addresses/${addressId}` : '/api/frontend/addresses', {
        method: isEditing ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          ...formData,
          alternate_phone: formData.alternate_phone || undefined,
          address_line2: formData.address_line2 || undefined,
          landmark: formData.landmark || undefined,
          country: 'Pakistan',
        }),
      })
      const data = await res.json()
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, isEditing ? t('updateFailed') : t('saveFailed')))
        return
      }
      toast.success(isEditing ? t('updated') : t('saved'))
      router.push('/account/addresses')
    } catch {
      toast.error(t('networkError'))
    } finally {
      setSaving(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        {/* Address Type */}
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('addressType')} *</label>
          <select
            value={formData.address_type}
            onChange={(e) => setField('address_type', e.target.value as AddressFormData['address_type'])}
            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 transition"
          >
            <option value="home">{t('typeHome')}</option>
            <option value="work">{t('typeWork')}</option>
            <option value="other">{t('typeOther')}</option>
          </select>
        </div>

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

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

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

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

        {/* Address Line 2 */}
        <div className="md:col-span-2">
          <label className="block text-dark font-medium mb-2 text-sm">{t('addressLine2')}</label>
          <input
            type="text"
            value={formData.address_line2}
            onChange={(e) => setField('address_line2', e.target.value)}
            placeholder={t('addressLine2Placeholder')}
            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 transition"
          />
        </div>

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

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

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

        {/* Landmark */}
        <div>
          <label className="block text-dark font-medium mb-2 text-sm">{t('landmark')}</label>
          <input
            type="text"
            value={formData.landmark}
            onChange={(e) => setField('landmark', e.target.value)}
            placeholder={t('landmarkPlaceholder')}
            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 transition"
          />
        </div>
      </div>

      {/* Default Address Checkbox */}
      <label className="flex items-center gap-2 cursor-pointer">
        <input
          type="checkbox"
          checked={formData.is_default}
          onChange={(e) => setField('is_default', e.target.checked)}
          className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
        />
        <span className="text-sm text-dark">{t('setAsDefault')}</span>
      </label>

      {/* Form Actions */}
      <div className="flex gap-3 pt-4">
        <button
          type="submit"
          disabled={saving}
          className="flex items-center gap-2 px-6 py-2.5 bg-gradient-primary text-white rounded-lg font-medium hover:shadow-md transition disabled:opacity-50"
        >
          <Save size={16} />
          {saving ? t('saving') : isEditing ? t('updateAddress') : t('saveAddress')}
        </button>
        <button
          type="button"
          onClick={() => router.back()}
          className="flex items-center gap-2 px-6 py-2.5 border border-gray-200 text-dark rounded-lg font-medium hover:bg-gray-50 transition"
        >
          <X size={16} />
          {t('cancel')}
        </button>
      </div>
    </form>
  )
}
