'use client'

import { useEffect, useState } from 'react'
import { Link } from '@/i18n/navigation'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { MapPin, Edit2, Trash2, Plus, Check } from 'lucide-react'
import { getApiErrorMessage } from '@/lib/utils/apiError'

interface Address {
  id: string
  full_name: string
  phone: string
  address_line1: string
  address_line2: string | null
  city: string
  state: string
  postal_code: string
  address_type: 'home' | 'work' | 'other'
  is_default: boolean
  landmark: string | null
}

export default function AddressList() {
  const t = useTranslations('Account.addresses')
  const [addresses, setAddresses] = useState<Address[]>([])
  const [loading, setLoading] = useState(true)
  const [busyId, setBusyId] = useState<string | null>(null)

  const typeLabels: Record<Address['address_type'], string> = {
    home: t('typeHome'),
    work: t('typeWork'),
    other: t('typeOther'),
  }

  const load = () => {
    fetch('/api/frontend/addresses', { credentials: 'include' })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) setAddresses(data.data)
      })
      .finally(() => setLoading(false))
  }

  useEffect(() => { load() }, [])

  const setDefaultAddress = async (id: string) => {
    setBusyId(id)
    try {
      const res = await fetch(`/api/frontend/addresses/${id}`, { method: 'PATCH', credentials: 'include' })
      const data = await res.json()
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, t('setDefaultFailed')))
        return
      }
      load()
    } catch {
      toast.error(t('networkError'))
    } finally {
      setBusyId(null)
    }
  }

  const deleteAddress = async (id: string) => {
    setBusyId(id)
    try {
      const res = await fetch(`/api/frontend/addresses/${id}`, { method: 'DELETE', credentials: 'include' })
      const data = await res.json()
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, t('deleteFailed')))
        return
      }
      toast.success(t('deleted'))
      load()
    } catch {
      toast.error(t('networkError'))
    } finally {
      setBusyId(null)
    }
  }

  if (loading) {
    return (
      <div className="text-center py-12">
        <div className="animate-spin w-8 h-8 border-4 border-primary border-t-transparent rounded-full mx-auto" />
      </div>
    )
  }

  if (addresses.length === 0) {
    return (
      <div className="text-center py-12">
        <MapPin size={48} className="mx-auto text-gray-custom mb-3" />
        <h3 className="text-lg font-semibold text-dark mb-1">{t('empty')}</h3>
        <p className="text-gray-custom text-sm">{t('emptyDescription')}</p>
        <Link href="/account/addresses/add" className="inline-block mt-4 bg-gradient-primary text-white px-4 py-2 rounded-lg text-sm">
          {t('addNew')}
        </Link>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-end">
        <Link
          href="/account/addresses/add"
          className="flex items-center gap-2 px-4 py-2 bg-gradient-primary text-white rounded-lg text-sm font-medium hover:shadow-md transition"
        >
          <Plus size={16} />
          {t('addNew')}
        </Link>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {addresses.map((address) => (
          <div
            key={address.id}
            className={`relative border rounded-xl p-4 transition-all ${
              address.is_default ? 'border-primary bg-primary/5' : 'border-gray-200'
            } ${busyId === address.id ? 'opacity-60 pointer-events-none' : ''}`}
          >
            {address.is_default && (
              <span className="absolute top-4 right-4 text-primary text-xs font-medium flex items-center gap-1">
                <Check size={12} /> {t('default')}
              </span>
            )}

            <div className="flex items-start gap-3">
              <MapPin size={18} className={address.is_default ? 'text-primary' : 'text-gray-custom'} />
              <div className="flex-1">
                <h3 className="font-semibold text-dark">{typeLabels[address.address_type]}</h3>
                <p className="text-sm text-dark font-medium mt-1">{address.full_name}</p>
                <p className="text-sm text-gray-custom">
                  {address.address_line1}
                  {address.address_line2 && <>, {address.address_line2}</>}
                </p>
                <p className="text-sm text-gray-custom">
                  {address.city}, {address.state} {address.postal_code}
                </p>
                {address.landmark && <p className="text-sm text-gray-custom">{t('landmark')}: {address.landmark}</p>}
                <p className="text-sm text-gray-custom mt-1">{t('phone')}: {address.phone}</p>
              </div>
            </div>

            <div className="flex gap-3 mt-4 pt-3 border-t border-gray-100">
              {!address.is_default && (
                <button
                  onClick={() => setDefaultAddress(address.id)}
                  className="text-sm text-primary hover:underline flex items-center gap-1"
                >
                  {t('setDefault')}
                </button>
              )}
              <Link
                href={`/account/addresses/edit/${address.id}`}
                className="text-sm text-dark hover:text-primary flex items-center gap-1"
              >
                <Edit2 size={12} /> {t('edit')}
              </Link>
              <button
                onClick={() => deleteAddress(address.id)}
                className="text-sm text-red-500 hover:text-red-700 flex items-center gap-1"
              >
                <Trash2 size={12} /> {t('delete')}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
