'use client'

import { useCallback, useEffect, useState } from 'react'
import {
  getSuppliers,
  listSuppliers,
  createSupplier,
  updateSupplier,
  SupplierProduct,
  SupplierRecord,
} from '@/lib/api/agent'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Spinner } from '@/components/ui/Spinner'
import { Skeleton } from '@/components/ui/Skeleton'
import { EmptyState } from '@/components/ui/EmptyState'
import { ErrorState } from '@/components/ui/ErrorState'
import { useToast } from '@/components/ui/Toast'
import { getMe } from '@/lib/api/agent'
import { formatCurrency } from '@/lib/types'
import { Truck, RefreshCw, Star, UserPlus, Pencil, X, Mail, Phone, MapPin } from 'lucide-react'

interface SupplierFormState {
  id: string | null
  name: string
  email: string
  phone: string
  address: string
}

const EMPTY_FORM: SupplierFormState = { id: null, name: '', email: '', phone: '', address: '' }

export default function SuppliersPage() {
  const { toast } = useToast()
  const [items, setItems] = useState<SupplierProduct[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')

  const [isAdmin, setIsAdmin] = useState(false)
  const [directory, setDirectory] = useState<SupplierRecord[]>([])
  const [form, setForm] = useState<SupplierFormState | null>(null)
  const [formError, setFormError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  const loadDirectory = useCallback(async () => {
    const res = await listSuppliers()
    if (res.success) setDirectory(res.data.suppliers)
  }, [])

  useEffect(() => {
    getMe().then(res => { if (res.success && res.data.role === 'admin') setIsAdmin(true) }).catch(() => {})
    loadDirectory().catch(() => undefined)
  }, [loadDirectory])

  useEffect(() => {
    let mounted = true
    async function load() {
      try {
        const res = await getSuppliers()
        if (!res.success) throw new Error(res.message)
        if (mounted) setItems(res.data.items)
      } catch (err) {
        if (mounted) setError(err instanceof Error ? err.message : 'Failed to load suppliers')
      } finally {
        if (mounted) setLoading(false)
      }
    }
    load()
    const interval = setInterval(load, 10000)
    return () => { clearInterval(interval) }
  }, [])

  const filtered = items.filter(item =>
    item.supplier?.name.toLowerCase().includes(search.toLowerCase()) ||
    item.product?.name.toLowerCase().includes(search.toLowerCase())
  )

  if (loading) {
    return (
      <div className="space-y-6">
        <div><h1 className="text-2xl font-bold">Suppliers</h1></div>
        <Card><CardContent className="p-6"><div className="space-y-4">{Array.from({length:5}).map((_,i)=>(<div key={i} className="flex items-center gap-4"><Skeleton className="h-12 w-12 rounded-lg"/><div className="flex-1 space-y-2"><Skeleton className="h-4 w-1/2"/><Skeleton className="h-3 w-1/3"/></div></div>))}</div></CardContent></Card>
      </div>
    )
  }

  if (error) return <ErrorState message={error} onRetry={() => window.location.reload()} />

  function validateForm(): string | null {
    if (!form) return null
    if (form.name.trim().length < 2) return 'Supplier name is required.'
    if (form.email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim())) {
      return 'Please enter a valid email address.'
    }
    return null
  }

  async function handleSaveSupplier() {
    if (!form) return
    const problem = validateForm()
    if (problem) {
      setFormError(problem)
      return
    }
    setSaving(true)
    const payload = {
      name: form.name.trim(),
      email: form.email.trim() || null,
      phone: form.phone.trim() || null,
      address: form.address.trim() || null,
    }
    const res = form.id
      ? await updateSupplier(form.id, payload)
      : await createSupplier(payload)
    setSaving(false)
    if (!res.success) {
      toast({ title: res.message, variant: 'destructive' })
      return
    }
    toast({
      title: form.id ? 'Supplier updated' : 'Supplier added',
      description: payload.email
        ? 'Their email is now used for order communications.'
        : undefined,
      variant: 'success',
    })
    setForm(null)
    loadDirectory().catch(() => undefined)
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Suppliers</h1>
          <p className="text-gray-500 dark:text-gray-400">Manage supplier contacts and catalog pricing</p>
        </div>
        <input
          type="text"
          placeholder="Search supplier or product..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="w-full sm:w-64 h-10 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:border-gray-600 dark:bg-gray-800"
        />
      </div>

      {isAdmin && (
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="flex items-center gap-2 text-base">
              <Truck className="h-4 w-4" /> Supplier Directory ({directory.length})
            </CardTitle>
            {!form ? (
              <Button size="sm" onClick={() => setForm({ ...EMPTY_FORM })}>
                <UserPlus className="h-4 w-4 mr-1" /> Add Supplier
              </Button>
            ) : (
              <Button size="sm" variant="ghost" onClick={() => setForm(null)}>
                <X className="h-4 w-4 mr-1" /> Cancel
              </Button>
            )}
          </CardHeader>
          <CardContent className="space-y-4">
            {form && (
              <div className="rounded-lg border border-gray-200 p-4 space-y-3 dark:border-gray-700">
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  {form.id ? 'Edit supplier' : 'New supplier — their contact info is used for order communications'}
                </p>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">                  <div>
                    <label htmlFor="sup-name" className="text-xs font-medium">Name *</label>
                    <Input id="sup-name" value={form.name} maxLength={160}
                      onChange={e => setForm({ ...form, name: e.target.value })}
                      placeholder="Kigali Wholesale Electronics Ltd" />
                  </div>
                  <div>
                    <label htmlFor="sup-email" className="text-xs font-medium">Email</label>
                    <Input id="sup-email" type="email" value={form.email} maxLength={160}
                      onChange={e => setForm({ ...form, email: e.target.value })}
                      placeholder="orders@supplier.rw" />
                  </div>
                  <div>
                    <label htmlFor="sup-phone" className="text-xs font-medium">Phone / WhatsApp</label>
                    <Input id="sup-phone" value={form.phone} maxLength={40}
                      onChange={e => setForm({ ...form, phone: e.target.value })}
                      placeholder="+250 788 000 000" />
                  </div>
                  <div>
                    <label htmlFor="sup-address" className="text-xs font-medium">Address</label>
                    <Input id="sup-address" value={form.address} maxLength={300}
                      onChange={e => setForm({ ...form, address: e.target.value })}
                      placeholder="Nyarugenge, Kigali" />
                  </div>
                </div>
                {formError && (
                  <p className="text-sm font-medium text-red-600 dark:text-red-400" role="alert">
                    {formError}
                  </p>
                )}
                <Button size="sm" disabled={saving} onClick={handleSaveSupplier}>
                  {saving ? 'Saving…' : form.id ? 'Save changes' : 'Add supplier'}
                </Button>
              </div>
            )}
            {directory.length === 0 && !form ? (
              <EmptyState icon={Truck} title="No suppliers yet"
                description="Add your first real supplier with their contact details." />
            ) : (
              <ul className="divide-y divide-gray-100 dark:divide-gray-800">
                {directory.map(sup => (
                  <li key={sup.id} className="flex flex-col gap-2 py-3 sm:flex-row sm:items-center sm:justify-between">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-gray-900 dark:text-white">{sup.name}</span>
                        {!sup.active && <Badge variant="secondary">Inactive</Badge>}
                      </div>
                      <p className="mt-0.5 flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
                        {sup.email && (<span className="inline-flex items-center gap-1"><Mail className="h-3 w-3" />{sup.email}</span>)}
                        {sup.phone && (<span className="inline-flex items-center gap-1"><Phone className="h-3 w-3" />{sup.phone}</span>)}
                        {sup.address && (<span className="inline-flex items-center gap-1"><MapPin className="h-3 w-3" />{sup.address}</span>)}
                        <span>{sup.product_count ?? 0} catalog link(s)</span>
                      </p>
                    </div>
                    <Button size="sm" variant="ghost"
                      onClick={() => setForm({
                        id: sup.id, name: sup.name, email: sup.email ?? '',
                        phone: sup.phone ?? '', address: sup.address ?? '',
                      })}>
                      <Pencil className="h-3.5 w-3.5 mr-1" /> Edit
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="flex items-center gap-2"><Truck className="h-5 w-5" /> Supplier Catalog</CardTitle>
        </CardHeader>
        <CardContent>
          {filtered.length === 0 ? (
            <EmptyState icon={Truck} title="No supplier products" description={search ? 'Try adjusting your search' : 'No supplier catalog entries'} />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Supplier</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Reliability</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Product</th>
                    <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Unit Cost</th>
                    <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Available</th>
                    <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Delivery</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Updated</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {filtered.map(item => (
                    <tr key={item.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                      <td className="px-4 py-3">
                        <div className="font-medium text-gray-900 dark:text-white">{item.supplier?.name}</div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-1">
                          <Star className="h-3.5 w-3.5 fill-current text-amber-500" />
                          <span className="text-sm font-medium">{(item.supplier?.reliability_score || 0) * 100}%</span>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="font-medium text-gray-900 dark:text-white">{item.product?.name}</div>
                        <div className="text-xs text-gray-500">{item.product?.sku}</div>
                      </td>
                      <td className="px-4 py-3 text-right font-medium">{formatCurrency(item.unit_cost)}</td>
                      <td className="px-4 py-3 text-right text-gray-500">{item.available_quantity}</td>
                      <td className="px-4 py-3 text-right">{item.delivery_days} day(s)</td>
                      <td className="px-4 py-3 text-sm text-gray-500">{item.last_updated ? new Date(item.last_updated).toLocaleDateString() : '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}