'use client'

import { Fragment, useEffect, useState, useCallback } from 'react'
import {
  getInventory,
  getSuppliers,
  InventoryItem,
  SupplierProduct,
  receiveStock,
  adjustStock,
  getStockMovements,
  listDeliveryEvents,
  confirmDelivery,
  rejectDelivery,
  StockMovement,
  DeliveryEvent,
} from '@/lib/api/agent'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import { Skeleton } from '@/components/ui/Skeleton'
import { EmptyState } from '@/components/ui/EmptyState'
import { ErrorState } from '@/components/ui/ErrorState'
import { formatCurrency } from '@/lib/types'
import {
  applyInventoryFilters,
  INVENTORY_FILTERS,
  itemStockStatus,
  STOCK_STATUS_META,
  type InventoryStatusFilter,
} from '@/lib/inventory-status'
import {
  Package,
  AlertTriangle,
  ChevronDown,
  ChevronUp,
  Truck,
  Plus,
  Minus,
  Clock,
  CheckCircle,
  XCircle,
  PackageCheck,
  Wrench,
} from 'lucide-react'
import { cn } from '@/lib/utils'

type Tab = 'inventory' | 'movements' | 'deliveries'

const REASON_OPTIONS: { value: 'adjustment' | 'damage' | 'loss' | 'transfer'; label: string }[] = [
  { value: 'adjustment', label: 'Adjustment' },
  { value: 'damage', label: 'Damage' },
  { value: 'loss', label: 'Loss' },
  { value: 'transfer', label: 'Transfer' },
]

export default function InventoryPage() {
  const [items, setItems] = useState<InventoryItem[]>([])
  const [offerings, setOfferings] = useState<SupplierProduct[] | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<InventoryStatusFilter>('all')
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [tab, setTab] = useState<Tab>('inventory')

  // Stock operations state
  const [receiveQty, setReceiveQty] = useState<Record<string, string>>({})
  const [adjustDelta, setAdjustDelta] = useState<Record<string, string>>({})
  const [adjustReason, setAdjustReason] = useState<Record<string, string>>({})
  const [opLoading, setOpLoading] = useState<Record<string, boolean>>({})
  const [opError, setOpError] = useState<Record<string, string | null>>({})
  const [opSuccess, setOpSuccess] = useState<Record<string, string | null>>({})

  // Movements state
  const [movements, setMovements] = useState<StockMovement[]>([])
  const [movementsLoading, setMovementsLoading] = useState(false)
  const [movementsError, setMovementsError] = useState<string | null>(null)
  const [movementFilter, setMovementFilter] = useState<string>('')

  // Deliveries state
  const [deliveries, setDeliveries] = useState<DeliveryEvent[]>([])
  const [deliveriesLoading, setDeliveriesLoading] = useState(false)
  const [deliveriesError, setDeliveriesError] = useState<string | null>(null)
  const [deliveryStatusFilter, setDeliveryStatusFilter] = useState('dispatched')
  const [confirmQty, setConfirmQty] = useState<Record<string, string>>({})
  const [confirmLoading, setConfirmLoading] = useState<Record<string, boolean>>({})
  const [confirmMsg, setConfirmMsg] = useState<Record<string, string | null>>({})

  const loadInventory = useCallback(async () => {
    try {
      const res = await getInventory()
      if (!res.success) throw new Error(res.message)
      setItems(res.data.items)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load inventory')
    } finally {
      setLoading(false)
    }
  }, [])

  const loadMovements = useCallback(async () => {
    setMovementsLoading(true)
    setMovementsError(null)
    try {
      const res = await getStockMovements({
        reason: movementFilter || undefined,
        limit: 50,
      })
      if (!res.success) throw new Error(res.message)
      setMovements(res.data.movements)
    } catch (err) {
      setMovementsError(err instanceof Error ? err.message : 'Failed to load movements')
    } finally {
      setMovementsLoading(false)
    }
  }, [movementFilter])

  const loadDeliveries = useCallback(async () => {
    setDeliveriesLoading(true)
    setDeliveriesError(null)
    try {
      const res = await listDeliveryEvents({
        status: deliveryStatusFilter || undefined,
        limit: 50,
      })
      if (!res.success) throw new Error(res.message)
      setDeliveries(res.data.events)
    } catch (err) {
      setDeliveriesError(err instanceof Error ? err.message : 'Failed to load deliveries')
    } finally {
      setDeliveriesLoading(false)
    }
  }, [deliveryStatusFilter])

  useEffect(() => {
    loadInventory()
    const interval = setInterval(loadInventory, 10000)
    return () => { clearInterval(interval) }
  }, [loadInventory])

  useEffect(() => {
    if (tab === 'movements') loadMovements()
    if (tab === 'deliveries') loadDeliveries()
  }, [tab, loadMovements, loadDeliveries])

  async function toggleExpanded(item: InventoryItem) {
    const id = item.id
    if (expandedId === id) { setExpandedId(null); return }
    setExpandedId(id)
    if (offerings) return
    try {
      const res = await getSuppliers()
      if (res.success) setOfferings(res.data.items)
    } catch {
      // detail panel shows a hint instead
    }
  }

  async function handleReceive(productId: string) {
    const qty = parseInt(receiveQty[productId] || '0', 10)
    if (qty < 1) {
      setOpError(prev => ({ ...prev, [productId]: 'Quantity must be at least 1' }))
      return
    }
    setOpLoading(prev => ({ ...prev, [productId]: true }))
    setOpError(prev => ({ ...prev, [productId]: null }))
    setOpSuccess(prev => ({ ...prev, [productId]: null }))
    try {
      const res = await receiveStock({ product_id: productId, quantity: qty })
      if (!res.success) throw new Error(res.message)
      setOpSuccess(prev => ({ ...prev, [productId]: `Received ${qty} units` }))
      setReceiveQty(prev => ({ ...prev, [productId]: '' }))
      loadInventory()
    } catch (err) {
      setOpError(prev => ({ ...prev, [productId]: err instanceof Error ? err.message : 'Failed' }))
    } finally {
      setOpLoading(prev => ({ ...prev, [productId]: false }))
    }
  }

  async function handleAdjust(productId: string) {
    const delta = parseInt(adjustDelta[productId] || '0', 10)
    const reason = (adjustReason[productId] || 'adjustment') as 'adjustment' | 'damage' | 'loss' | 'transfer'
    if (delta === 0) {
      setOpError(prev => ({ ...prev, [productId]: 'Delta cannot be zero' }))
      return
    }
    setOpLoading(prev => ({ ...prev, [productId]: true }))
    setOpError(prev => ({ ...prev, [productId]: null }))
    setOpSuccess(prev => ({ ...prev, [productId]: null }))
    try {
      const res = await adjustStock({ product_id: productId, delta, reason })
      if (!res.success) throw new Error(res.message)
      setOpSuccess(prev => ({ ...prev, [productId]: `Adjusted by ${delta > 0 ? '+' : ''}${delta} (${reason})` }))
      setAdjustDelta(prev => ({ ...prev, [productId]: '' }))
      loadInventory()
    } catch (err) {
      setOpError(prev => ({ ...prev, [productId]: err instanceof Error ? err.message : 'Failed' }))
    } finally {
      setOpLoading(prev => ({ ...prev, [productId]: false }))
    }
  }

  async function handleConfirmDelivery(eventId: string) {
    const qty = parseInt(confirmQty[eventId] || '0', 10)
    if (qty < 1) {
      setConfirmMsg(prev => ({ ...prev, [eventId]: 'Enter quantity received' }))
      return
    }
    setConfirmLoading(prev => ({ ...prev, [eventId]: true }))
    setConfirmMsg(prev => ({ ...prev, [eventId]: null }))
    try {
      const res = await confirmDelivery(eventId, { received_quantity: qty })
      if (!res.success) throw new Error(res.message)
      setConfirmMsg(prev => ({ ...prev, [eventId]: `Confirmed ${qty} units received` }))
      setConfirmQty(prev => ({ ...prev, [eventId]: '' }))
      loadDeliveries()
      loadInventory()
    } catch (err) {
      setConfirmMsg(prev => ({ ...prev, [eventId]: err instanceof Error ? err.message : 'Failed' }))
    } finally {
      setConfirmLoading(prev => ({ ...prev, [eventId]: false }))
    }
  }

  async function handleRejectDelivery(eventId: string) {
    setConfirmLoading(prev => ({ ...prev, [eventId]: true }))
    setConfirmMsg(prev => ({ ...prev, [eventId]: null }))
    try {
      const res = await rejectDelivery(eventId, 'Rejected from dashboard')
      if (!res.success) throw new Error(res.message)
      setConfirmMsg(prev => ({ ...prev, [eventId]: 'Delivery rejected' }))
      loadDeliveries()
    } catch (err) {
      setConfirmMsg(prev => ({ ...prev, [eventId]: err instanceof Error ? err.message : 'Failed' }))
    } finally {
      setConfirmLoading(prev => ({ ...prev, [eventId]: false }))
    }
  }

  const filtered = applyInventoryFilters(items, search, statusFilter)

  const pendingDeliveries = deliveries.filter(d => d.status === 'dispatched' || d.status === 'expected')
  const lowStockCount = items.filter(i => itemStockStatus(i) === 'low_stock').length
  const outOfStockCount = items.filter(i => itemStockStatus(i) === 'out_of_stock').length

  if (loading) {
    return (
      <div className="space-y-6">
        <div><h1 className="text-2xl font-bold">Inventory</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()} />

  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">Inventory</h1>
          <p className="text-gray-500 dark:text-gray-400">Manage stock, receive goods, and adjust inventory</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 rounded-lg bg-gray-100 p-1 dark:bg-gray-800" role="tablist">
        <button
          role="tab"
          aria-selected={tab === 'inventory'}
          onClick={() => setTab('inventory')}
          className={cn(
            'flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors',
            tab === 'inventory' ? 'bg-white text-gray-900 shadow dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-900 dark:text-gray-400'
          )}
        >
          <Package className="h-4 w-4" /> Stock Levels
          {(lowStockCount + outOfStockCount) > 0 && (
            <Badge variant="warning" className="ml-1">{lowStockCount + outOfStockCount}</Badge>
          )}
        </button>
        <button
          role="tab"
          aria-selected={tab === 'deliveries'}
          onClick={() => setTab('deliveries')}
          className={cn(
            'flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors',
            tab === 'deliveries' ? 'bg-white text-gray-900 shadow dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-900 dark:text-gray-400'
          )}
        >
          <Truck className="h-4 w-4" /> Pending Deliveries
          {pendingDeliveries.length > 0 && (
            <Badge variant="warning" className="ml-1">{pendingDeliveries.length}</Badge>
          )}
        </button>
        <button
          role="tab"
          aria-selected={tab === 'movements'}
          onClick={() => setTab('movements')}
          className={cn(
            'flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors',
            tab === 'movements' ? 'bg-white text-gray-900 shadow dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-900 dark:text-gray-400'
          )}
        >
          <Clock className="h-4 w-4" /> Stock Movements
        </button>
      </div>

      {/* ============ INVENTORY TAB ============ */}
      {tab === 'inventory' && (
        <>
          <div className="flex gap-2">
            <input
              type="text"
              placeholder="Search products..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              aria-label="Search products"
              className="flex h-10 w-full sm:w-64 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>

          <div className="flex flex-wrap gap-2" role="group" aria-label="Filter by stock status">
            {INVENTORY_FILTERS.map(f => (
              <button
                key={f.value}
                type="button"
                onClick={() => setStatusFilter(f.value)}
                aria-pressed={statusFilter === f.value}
                className={cn(
                  'px-3 py-1.5 rounded-full text-sm font-medium border transition-colors',
                  statusFilter === f.value
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700'
                )}
              >
                {f.label}
              </button>
            ))}
          </div>

          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <Card><CardContent className="p-6">
              <p className="text-sm text-gray-500 dark:text-gray-400">Total Products</p>
              <p className="text-2xl font-bold">{items.length}</p>
            </CardContent></Card>
            <Card><CardContent className="p-6">
              <p className="text-sm text-gray-500 dark:text-gray-400">Out of Stock</p>
              <p className="text-2xl font-bold text-red-600">{outOfStockCount}</p>
            </CardContent></Card>
            <Card><CardContent className="p-6">
              <p className="text-sm text-gray-500 dark:text-gray-400">Low Stock</p>
              <p className="text-2xl font-bold text-amber-600">{lowStockCount}</p>
            </CardContent></Card>
            <Card><CardContent className="p-6">
              <p className="text-sm text-gray-500 dark:text-gray-400">Total Value</p>
              <p className="text-2xl font-bold">{formatCurrency(items.reduce((sum, i) => sum + i.quantity * (i.product?.unit_price || 0), 0))}</p>
            </CardContent></Card>
          </div>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Package className="h-5 w-5" /> Stock Levels</CardTitle>
            </CardHeader>
            <CardContent>
              {filtered.length === 0 ? (
                <EmptyState icon={Package} title="No products found" description={search || statusFilter !== 'all' ? 'Try adjusting your search or filters' : 'No inventory records'} />
              ) : (
                <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">Product</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">SKU</th>
                        <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Qty</th>
                        <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Reserved</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-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                      {filtered.map(item => {
                        const available = Math.max(item.quantity - item.reserved_quantity, 0)
                        const statusKey = itemStockStatus(item)
                        const meta = STOCK_STATUS_META[statusKey]
                        const expanded = expandedId === item.id
                        const pid = item.product_id
                        return (
                          <Fragment key={item.id}>
                            <tr
                              onClick={() => void toggleExpanded(item)}
                              className={cn(
                                'cursor-pointer transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50',
                                statusKey !== 'available' && 'bg-amber-50/40 dark:bg-amber-900/10',
                                expanded && 'bg-gray-50 dark:bg-gray-800'
                              )}
                              aria-expanded={expanded}
                            >
                              <td className="px-4 py-3">
                                <div className="flex items-center gap-2">
                                  {expanded ? <ChevronUp className="h-4 w-4 text-gray-400" /> : <ChevronDown className="h-4 w-4 text-gray-400" />}
                                  <div>
                                    <div className="font-medium text-gray-900 dark:text-white">{item.product?.name}</div>
                                    <div className="text-xs text-gray-500">{item.product_id.slice(0,8)}</div>
                                  </div>
                                </div>
                              </td>
                              <td className="px-4 py-3 text-sm text-gray-500">{item.product?.sku}</td>
                              <td className="px-4 py-3 text-right font-medium">{item.quantity}</td>
                              <td className="px-4 py-3 text-right text-gray-500">{item.reserved_quantity}</td>
                              <td className="px-4 py-3 text-right font-semibold">{available}</td>
                              <td className="px-4 py-3"><Badge variant={meta.badge}>{meta.label}</Badge></td>
                              <td className="px-4 py-3">
                                <div className="flex gap-1">
                                  <button
                                    type="button"
                                    onClick={(e) => { e.stopPropagation(); toggleExpanded(item) }}
                                    className="inline-flex items-center gap-1 rounded-md bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100 dark:bg-emerald-900/30 dark:text-emerald-400"
                                  >
                                    <Plus className="h-3 w-3" /> Receive
                                  </button>
                                  <button
                                    type="button"
                                    onClick={(e) => { e.stopPropagation(); toggleExpanded(item) }}
                                    className="inline-flex items-center gap-1 rounded-md bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-700 hover:bg-amber-100 dark:bg-amber-900/30 dark:text-amber-400"
                                  >
                                    <Wrench className="h-3 w-3" /> Adjust
                                  </button>
                                </div>
                              </td>
                            </tr>
                            {expanded && (
                              <tr className="bg-gray-50/80 dark:bg-gray-800/60">
                                <td colSpan={7} className="px-4 py-4">
                                  <div className="space-y-4">
                                    {/* Success/Error messages */}
                                    {opSuccess[pid] && (
                                      <div className="rounded-md bg-emerald-50 p-3 text-sm text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400">
                                        {opSuccess[pid]}
                                      </div>
                                    )}
                                    {opError[pid] && (
                                      <div className="rounded-md bg-red-50 p-3 text-sm text-red-700 dark:bg-red-900/30 dark:text-red-400">
                                        {opError[pid]}
                                      </div>
                                    )}

                                    {/* Receive Stock */}
                                    <div className="rounded-lg border border-emerald-200 bg-emerald-50/50 p-4 dark:border-emerald-800 dark:bg-emerald-900/20">
                                      <p className="text-sm font-medium text-emerald-800 dark:text-emerald-200 mb-3 flex items-center gap-2">
                                        <PackageCheck className="h-4 w-4" />
                                        Receive Stock — {item.product?.name}
                                      </p>
                                      <div className="flex flex-wrap items-end gap-3">
                                        <div>
                                          <label className="block text-xs text-emerald-600 dark:text-emerald-400 mb-1">Quantity</label>
                                          <input
                                            type="number"
                                            min={1}
                                            value={receiveQty[pid] || ''}
                                            onChange={e => setReceiveQty(prev => ({ ...prev, [pid]: e.target.value }))}
                                            className="h-9 w-24 rounded-md border border-emerald-300 bg-white px-2 text-sm dark:border-emerald-700 dark:bg-gray-800"
                                            placeholder="Qty"
                                          />
                                        </div>
                                        <button
                                          type="button"
                                          disabled={opLoading[pid]}
                                          onClick={() => void handleReceive(pid)}
                                          className="inline-flex items-center gap-1.5 rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                                        >
                                          <PackageCheck className="h-4 w-4" />
                                          {opLoading[pid] ? 'Receiving...' : 'Confirm Receipt'}
                                        </button>
                                      </div>
                                    </div>

                                    {/* Adjust Stock */}
                                    <div className="rounded-lg border border-amber-200 bg-amber-50/50 p-4 dark:border-amber-800 dark:bg-amber-900/20">
                                      <p className="text-sm font-medium text-amber-800 dark:text-amber-200 mb-3 flex items-center gap-2">
                                        <Wrench className="h-4 w-4" />
                                        Adjust Stock — {item.product?.name}
                                      </p>
                                      <div className="flex flex-wrap items-end gap-3">
                                        <div>
                                          <label className="block text-xs text-amber-600 dark:text-amber-400 mb-1">Delta (+/-)</label>
                                          <input
                                            type="number"
                                            min={-10000}
                                            max={10000}
                                            value={adjustDelta[pid] || ''}
                                            onChange={e => setAdjustDelta(prev => ({ ...prev, [pid]: e.target.value }))}
                                            className="h-9 w-24 rounded-md border border-amber-300 bg-white px-2 text-sm dark:border-amber-700 dark:bg-gray-800"
                                            placeholder="-5"
                                          />
                                        </div>
                                        <div>
                                          <label className="block text-xs text-amber-600 dark:text-amber-400 mb-1">Reason</label>
                                          <select
                                            value={adjustReason[pid] || 'adjustment'}
                                            onChange={e => setAdjustReason(prev => ({ ...prev, [pid]: e.target.value }))}
                                            className="h-9 rounded-md border border-amber-300 bg-white px-2 text-sm dark:border-amber-700 dark:bg-gray-800"
                                          >
                                            {REASON_OPTIONS.map(o => (
                                              <option key={o.value} value={o.value}>{o.label}</option>
                                            ))}
                                          </select>
                                        </div>
                                        <button
                                          type="button"
                                          disabled={opLoading[pid]}
                                          onClick={() => void handleAdjust(pid)}
                                          className="inline-flex items-center gap-1.5 rounded-md bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700 disabled:opacity-50"
                                        >
                                          <Wrench className="h-4 w-4" />
                                          {opLoading[pid] ? 'Adjusting...' : 'Apply Adjustment'}
                                        </button>
                                      </div>
                                    </div>

                                    {/* Supplier restocking options */}
                                    {statusKey !== 'available' && (
                                      <div>
                                        {offerings === null ? (
                                          <p className="text-sm text-gray-500 dark:text-gray-400">Loading supplier options…</p>
                                        ) : (
                                          (() => {
                                            const productOfferings = (offerings || [])
                                              .filter(o => o.product_id === pid)
                                              .sort((a, b) => a.unit_cost - b.unit_cost)
                                              .slice(0, 3)
                                            if (productOfferings.length === 0) {
                                              return (
                                                <p className="text-sm text-gray-500 dark:text-gray-400">
                                                  No supplier offers found. Visit{' '}
                                                  <a href="/dashboard/suppliers" className="text-indigo-600 hover:underline dark:text-indigo-400">Suppliers</a>.
                                                </p>
                                              )
                                            }
                                            return (
                                              <div>
                                                <p className="text-sm font-medium text-gray-700 dark:text-gray-200 mb-2 flex items-center gap-2">
                                                  <AlertTriangle className="h-4 w-4 text-amber-500" />
                                                  Supplier options for restocking:
                                                </p>
                                                <ul className="space-y-2">
                                                  {productOfferings.map(o => (
                                                    <li key={o.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-gray-600 dark:text-gray-300">
                                                      <span className="font-medium text-gray-900 dark:text-white">{o.supplier?.name || o.supplier_id.slice(0, 8)}</span>
                                                      <span>{formatCurrency(o.unit_cost)}/unit</span>
                                                      <span className="flex items-center gap-1"><Truck className="h-3.5 w-3.5 text-gray-400" />{o.delivery_days}d delivery</span>
                                                      <span>{o.available_quantity} available</span>
                                                    </li>
                                                  ))}
                                                </ul>
                                              </div>
                                            )
                                          })()
                                        )}
                                      </div>
                                    )}
                                  </div>
                                </td>
                              </tr>
                            )}
                          </Fragment>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}

      {/* ============ DELIVERIES TAB ============ */}
      {tab === 'deliveries' && (
        <>
          <div className="flex flex-wrap gap-2" role="group" aria-label="Filter by delivery status">
            {['dispatched', 'expected', 'confirmed', 'received', 'rejected'].map(s => (
              <button
                key={s}
                type="button"
                onClick={() => { setDeliveryStatusFilter(s); }}
                className={cn(
                  'px-3 py-1.5 rounded-full text-sm font-medium border transition-colors capitalize',
                  deliveryStatusFilter === s
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700'
                )}
              >
                {s}
              </button>
            ))}
          </div>

          {deliveriesLoading ? (
            <Card><CardContent className="p-6"><div className="space-y-4">{Array.from({length:3}).map((_,i)=>(<div key={i} className="flex items-center gap-4"><Skeleton className="h-10 w-10 rounded"/><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>
          ) : deliveriesError ? (
            <ErrorState message={deliveriesError} onRetry={loadDeliveries} />
          ) : deliveries.length === 0 ? (
            <EmptyState icon={Truck} title="No deliveries" description={deliveryStatusFilter !== 'all' ? `No ${deliveryStatusFilter} deliveries` : 'No delivery events found'} />
          ) : (
            <Card>
              <CardContent>
                <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">Event ID</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Purchase Request</th>
                        <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">Status</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Expected</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Action</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                      {deliveries.map(d => {
                        const canConfirm = d.status === 'dispatched' || d.status === 'expected'
                        return (
                          <tr key={d.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                            <td className="px-4 py-3 text-sm font-mono text-gray-500">{d.id.slice(0, 8)}</td>
                            <td className="px-4 py-3 text-sm font-mono">{d.purchase_request_id.slice(0, 8)}</td>
                            <td className="px-4 py-3 text-sm">{d.supplier_name || d.supplier_id.slice(0, 8)}</td>
                            <td className="px-4 py-3">
                              <Badge variant={d.status === 'received' ? 'success' : d.status === 'rejected' ? 'danger' : d.status === 'dispatched' ? 'warning' : 'info'}>
                                {d.status}
                              </Badge>
                            </td>
                            <td className="px-4 py-3 text-sm text-gray-500">
                              {d.expected_delivery_at ? new Date(d.expected_delivery_at).toLocaleDateString() : '—'}
                            </td>
                            <td className="px-4 py-3">
                              {canConfirm ? (
                                <div className="flex flex-wrap items-end gap-2">
                                  <div>
                                    <label className="block text-xs text-gray-500 mb-1">Received qty</label>
                                    <input
                                      type="number"
                                      min={1}
                                      value={confirmQty[d.id] || ''}
                                      onChange={e => setConfirmQty(prev => ({ ...prev, [d.id]: e.target.value }))}
                                      className="h-8 w-20 rounded border border-gray-300 bg-white px-2 text-sm dark:border-gray-600 dark:bg-gray-800"
                                      placeholder="Qty"
                                    />
                                  </div>
                                  <button
                                    type="button"
                                    disabled={confirmLoading[d.id]}
                                    onClick={() => void handleConfirmDelivery(d.id)}
                                    className="inline-flex items-center gap-1 rounded bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                                  >
                                    <CheckCircle className="h-3 w-3" /> Confirm
                                  </button>
                                  <button
                                    type="button"
                                    disabled={confirmLoading[d.id]}
                                    onClick={() => void handleRejectDelivery(d.id)}
                                    className="inline-flex items-center gap-1 rounded bg-red-100 px-3 py-1.5 text-xs font-medium text-red-700 hover:bg-red-200 disabled:opacity-50 dark:bg-red-900/30 dark:text-red-400"
                                  >
                                    <XCircle className="h-3 w-3" /> Reject
                                  </button>
                                </div>
                              ) : (
                                <span className="text-sm text-gray-400">—</span>
                              )}
                              {confirmMsg[d.id] && (
                                <p className="mt-1 text-xs text-gray-500">{confirmMsg[d.id]}</p>
                              )}
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}

      {/* ============ MOVEMENTS TAB ============ */}
      {tab === 'movements' && (
        <>
          <div className="flex flex-wrap gap-2" role="group" aria-label="Filter by movement reason">
            {['', 'receipt', 'adjustment', 'damage', 'loss', 'transfer', 'reservation', 'sale'].map(r => (
              <button
                key={r}
                type="button"
                onClick={() => setMovementFilter(r)}
                className={cn(
                  'px-3 py-1.5 rounded-full text-sm font-medium border transition-colors capitalize',
                  movementFilter === r
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700'
                )}
              >
                {r || 'All'}
              </button>
            ))}
          </div>

          {movementsLoading ? (
            <Card><CardContent className="p-6"><div className="space-y-4">{Array.from({length:3}).map((_,i)=>(<div key={i} className="flex items-center gap-4"><Skeleton className="h-10 w-10 rounded"/><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>
          ) : movementsError ? (
            <ErrorState message={movementsError} onRetry={loadMovements} />
          ) : movements.length === 0 ? (
            <EmptyState icon={Clock} title="No movements" description="No stock movements recorded yet" />
          ) : (
            <Card>
              <CardContent>
                <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">Time</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">Delta</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Reason</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Notes</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                      {movements.map(m => (
                        <tr key={m.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                          <td className="px-4 py-3 text-sm text-gray-500">{new Date(m.created_at).toLocaleString()}</td>
                          <td className="px-4 py-3 text-sm font-medium">{m.product_name || m.product_id.slice(0, 8)}</td>
                          <td className={cn('px-4 py-3 text-right font-mono font-semibold', m.delta > 0 ? 'text-emerald-600' : 'text-red-600')}>
                            {m.delta > 0 ? '+' : ''}{m.delta}
                          </td>
                          <td className="px-4 py-3">
                            <Badge variant={m.reason === 'receipt' ? 'success' : m.reason === 'damage' || m.reason === 'loss' ? 'danger' : 'info'}>
                              {m.reason}
                            </Badge>
                          </td>
                          <td className="px-4 py-3 text-sm text-gray-500 max-w-xs truncate">{m.notes || '—'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}
    </div>
  )
}
