'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import {
  getAllProductsForCatalog,
  getInventory,
  getSuppliers,
  createCatalogProduct,
  updateCatalogProduct,
  createCatalogSupplier,
  upsertSupplierProductLink,
  CatalogProduct,
  SupplierProduct,
} 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 { Skeleton } from '@/components/ui/Skeleton'
import { EmptyState } from '@/components/ui/EmptyState'
import { ErrorState } from '@/components/ui/ErrorState'
import { formatCurrency } from '@/lib/types'
import { useToast } from '@/components/ui/Toast'
import { Package, Search, Plus, Pencil, Truck, RefreshCw, X } from 'lucide-react'

interface FormState {
  name: string
  sku: string
  category: string
  description: string
  unit_price: string
  reorder_threshold: string
  is_public: boolean
}

const EMPTY_FORM: FormState = {
  name: '', sku: '', category: '', description: '',
  unit_price: '', reorder_threshold: '5', is_public: true,
}

export default function CatalogPage() {
  const { toast } = useToast()
  const [products, setProducts] = useState<CatalogProduct[]>([])
  const [inventory, setInventory] = useState<Record<string, number>>({})
  const [suppliers, setSuppliers] = useState<SupplierProduct[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')

  const [editing, setEditing] = useState<CatalogProduct | 'new' | null>(null)
  const [form, setForm] = useState<FormState>(EMPTY_FORM)
  const [saving, setSaving] = useState(false)
  const [formError, setFormError] = useState<string | null>(null)

  const [linking, setLinking] = useState(false)
  const [linkForm, setLinkForm] = useState({
    supplier_id: '', product_id: '', unit_cost: '',
    available_quantity: '', delivery_days: '1',
  })

  const load = useCallback(async () => {
    const [prodRes, invRes, supRes] = await Promise.all([
      getAllProductsForCatalog(),
      getInventory(),
      getSuppliers(),
    ])
    if (!prodRes.success) throw new Error(prodRes.message)
    setProducts(prodRes.data.products)
    if (invRes.success) {
      const map: Record<string, number> = {}
      for (const item of invRes.data.items) {
        map[item.product_id] = (item.quantity ?? 0) - (item.reserved_quantity ?? 0)
      }
      setInventory(map)
    }
    if (supRes.success) setSuppliers(supRes.data.items)
  }, [])

  useEffect(() => {
    let mounted = true
    load().catch(err => {
      if (mounted) setError(err instanceof Error ? err.message : 'Failed to load catalog')
    }).finally(() => { if (mounted) setLoading(false) })
    return () => { mounted = false }
  }, [load])

  const filtered = useMemo(
    () => products.filter(p =>
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      (p.sku ?? '').toLowerCase().includes(search.toLowerCase()) ||
      (p.category ?? '').toLowerCase().includes(search.toLowerCase())),
    [products, search]
  )

  function openCreate() {
    setEditing('new'); setForm(EMPTY_FORM); setFormError(null)
  }

  function openEdit(p: CatalogProduct) {
    setEditing(p)
    setForm({
      name: p.name, sku: p.sku ?? '', category: p.category ?? '',
      description: p.description ?? '', unit_price: String(p.unit_price),
      reorder_threshold: String(p.reorder_threshold), is_public: p.is_public,
    })
    setFormError(null)
  }

  async function handleSave() {
    const price = Number(form.unit_price)
    if (!form.name.trim()) { setFormError('Name is required.'); return }
    if (!Number.isFinite(price) || price < 0) {
      setFormError('Price must be a valid non-negative number.'); return
    }
    const threshold = Number(form.reorder_threshold || '5')
    if (!Number.isInteger(threshold) || threshold < 0) {
      setFormError('Reorder threshold must be a whole number ≥ 0.'); return
    }
    setSaving(true)
    setFormError(null)
    const payload = {
      name: form.name.trim(),
      sku: form.sku.trim() || null,
      category: form.category.trim() || null,
      description: form.description.trim() || null,
      unit_price: price,
      cost_price: null,
      reorder_threshold: threshold,
      is_public: form.is_public,
    }
    let res
    if (editing === 'new') {
      res = await createCatalogProduct(payload)
    } else if (editing) {
      res = await updateCatalogProduct(editing.id, payload)
    } else {
      res = { success: false as const, error_code: 'NO_TARGET', message: 'Nothing selected.' }
    }
    setSaving(false)
    if (!res.success) {
      setFormError(res.message)
      return
    }
    toast({ title: editing === 'new' ? 'Product created' : 'Product updated', variant: 'success' })
    setEditing(null)
    try { await load() } catch { /* keep list */ }
  }

  async function togglePublic(p: CatalogProduct) {
    const res = await updateCatalogProduct(p.id, { is_public: !p.is_public })
    if (res.success) {
      toast({ title: p.is_public ? 'Removed from storefront' : 'Published to storefront', variant: 'success' })
      try { await load() } catch { /* keep list */ }
    } else {
      toast({ title: 'Update failed', description: res.message, variant: 'destructive' })
    }
  }

  async function handleLink() {
    const cost = Number(linkForm.unit_cost)
    const qty = Number(linkForm.available_quantity)
    const days = Number(linkForm.delivery_days)
    if (!linkForm.supplier_id || !linkForm.product_id) {
      toast({ title: 'Select supplier and product', variant: 'destructive' }); return
    }
    if (!Number.isFinite(cost) || cost < 0 || !Number.isInteger(qty) || qty < 0 ||
        !Number.isInteger(days) || days < 0) {
      toast({ title: 'Invalid supplier-product values', variant: 'destructive' }); return
    }
    setLinking(true)
    const res = await upsertSupplierProductLink({
      supplier_id: linkForm.supplier_id,
      product_id: linkForm.product_id,
      unit_cost: cost,
      available_quantity: qty,
      delivery_days: days,
    })
    setLinking(false)
    if (!res.success) {
      toast({ title: 'Link failed', description: res.message, variant: 'destructive' })
    } else {
      toast({ title: 'Supplier product saved', variant: 'success' })
      setLinkForm({ supplier_id: '', product_id: '', unit_cost: '', available_quantity: '', delivery_days: '1' })
    }
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Catalog</h1>
        <div className="space-y-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full rounded-lg" />
          ))}
        </div>
      </div>
    )
  }

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

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Catalog</h1>
          <p className="text-gray-500 dark:text-gray-400">
            Products and suppliers powering the storefront and the agent
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={() => load().catch(() => undefined)}>
            <RefreshCw className="mr-2 h-4 w-4" /> Refresh
          </Button>
          <Button size="sm" onClick={openCreate}>
            <Plus className="mr-1 h-4 w-4" /> New product
          </Button>
        </div>
      </div>

      {/* Create / edit form */}
      {editing && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between text-base">
              <span className="flex items-center gap-2">
                <Pencil className="h-4 w-4" />
                {editing === 'new' ? 'New product' : `Edit ${editing.name}`}
              </span>
              <Button variant="ghost" size="sm" onClick={() => setEditing(null)} aria-label="Close">
                <X className="h-4 w-4" />
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {formError && (
              <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-400">
                {formError}
              </div>
            )}
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <div>
                <label className="text-xs font-medium text-gray-500">Name *</label>
                <Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Product name" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500">SKU</label>
                <Input value={form.sku} onChange={e => setForm({ ...form, sku: e.target.value })} placeholder="Auto-generated if empty" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500">Category</label>
                <Input value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} placeholder="e.g. Accessories" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500">Unit price * (≥ 0)</label>
                <Input type="number" min="0" step="0.01" value={form.unit_price}
                  onChange={e => setForm({ ...form, unit_price: e.target.value })} placeholder="0.00" />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500">Reorder threshold</label>
                <Input type="number" min="0" step="1" value={form.reorder_threshold}
                  onChange={e => setForm({ ...form, reorder_threshold: e.target.value })} />
              </div>
              <label className="flex items-center gap-2 pt-5 text-sm text-gray-700 dark:text-gray-300">
                <input type="checkbox" checked={form.is_public}
                  onChange={e => setForm({ ...form, is_public: e.target.checked })} />
                Show on public storefront
              </label>
            </div>
            <div>
              <label className="text-xs font-medium text-gray-500">Description</label>
              <textarea rows={2} value={form.description}
                onChange={e => setForm({ ...form, description: e.target.value })}
                className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-800 dark:text-white" />
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" size="sm" onClick={() => setEditing(null)}>Cancel</Button>
              <Button size="sm" disabled={saving} onClick={handleSave}>
                {saving ? 'Saving…' : editing === 'new' ? 'Create' : 'Save changes'}
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Products */}
      <Card>
        <CardHeader>
          <CardTitle className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 text-base">
            <span className="flex items-center gap-2"><Package className="h-4 w-4" /> Products ({filtered.length})</span>
            <div className="relative w-full sm:w-64">
              <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <Input value={search} onChange={e => setSearch(e.target.value)}
                placeholder="Search name / SKU / category" className="pl-8" aria-label="Search products" />
            </div>
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {filtered.length === 0 ? (
            <div className="p-6">
              <EmptyState icon={Package} title="No products" description="Create your first product to open the storefront." />
            </div>
          ) : (
            <ul className="divide-y divide-gray-100 dark:divide-gray-800">
              {filtered.map(p => (
                <li key={p.id} className="flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-semibold text-sm text-gray-900 dark:text-white">{p.name}</span>
                      {!p.active && <Badge variant="secondary">Disabled</Badge>}
                      <Badge variant={p.is_public ? 'success' : 'secondary'}>
                        {p.is_public ? 'On storefront' : 'Not published'}
                      </Badge>
                    </div>
                    <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400 truncate">
                      {p.sku ?? 'no SKU'} · {p.category ?? 'uncategorised'} · available {inventory[p.id] ?? 0}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 sm:flex-shrink-0">
                    <span className="mr-2 text-sm font-bold text-gray-900 dark:text-white">
                      {formatCurrency(p.unit_price)}
                    </span>
                    <Button size="sm" variant={p.is_public ? 'outline' : 'primary'}
                      onClick={() => togglePublic(p)} disabled={!p.active}>
                      {p.is_public ? 'Unpublish' : 'Publish'}
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => openEdit(p)}>
                      <Pencil className="h-3 w-3" />
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      {/* Suppliers */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Truck className="h-4 w-4" /> Suppliers ({suppliers.length})
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          {suppliers.length === 0 ? (
            <EmptyState icon={Truck} title="No suppliers yet" description="Suppliers provide stock to the agent's sourcing engine." />
          ) : (
            suppliers.map(s => (
              <div key={s.id} className="flex items-center justify-between gap-3 rounded-lg border border-gray-100 px-3 py-2 dark:border-gray-800">
                <div className="min-w-0">
                  <p className="text-sm font-medium text-gray-900 dark:text-white">{s.supplier?.name ?? s.supplier_id}</p>
                  <p className="truncate text-xs text-gray-500 dark:text-gray-400">
                    {s.product?.name ? `${s.product.name} · ` : ''}
                    cost {formatCurrency(s.unit_cost)} · {s.available_quantity} available · {s.delivery_days}-day lead
                    {typeof s.supplier?.reliability_score === 'number'
                      ? ` · ${(s.supplier.reliability_score * 100).toFixed(0)}% reliable`
                      : ''}
                  </p>
                </div>
              </div>
            ))
          )}
        </CardContent>
      </Card>

      {/* Link supplier ↔ product */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Link supplier to product</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
          <select aria-label="Supplier" value={linkForm.supplier_id}
            onChange={e => setLinkForm({ ...linkForm, supplier_id: e.target.value })}
            className="rounded-md border border-gray-200 bg-white px-2 py-2 text-sm dark:border-gray-700 dark:bg-gray-900">
            <option value="">— Supplier —</option>
            {[...new Map(suppliers.map(s => [s.supplier_id, s.supplier?.name ?? s.supplier_id])).entries()]
              .map(([id, name]) => <option key={id} value={id}>{name}</option>)}
          </select>
          <select aria-label="Product" value={linkForm.product_id}
            onChange={e => setLinkForm({ ...linkForm, product_id: e.target.value })}
            className="rounded-md border border-gray-200 bg-white px-2 py-2 text-sm dark:border-gray-700 dark:bg-gray-900">
            <option value="">— Product —</option>
            {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <Input type="number" min="0" step="0.01" placeholder="Unit cost"
            value={linkForm.unit_cost}
            onChange={e => setLinkForm({ ...linkForm, unit_cost: e.target.value })} />
          <Input type="number" min="0" step="1" placeholder="Available quantity"
            value={linkForm.available_quantity}
            onChange={e => setLinkForm({ ...linkForm, available_quantity: e.target.value })} />
          <Input type="number" min="0" step="1" placeholder="Delivery days"
            value={linkForm.delivery_days}
            onChange={e => setLinkForm({ ...linkForm, delivery_days: e.target.value })} />
          <Button disabled={linking} onClick={handleLink}>
            {linking ? 'Saving…' : 'Save link'}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
