'use client'

import { useEffect, useState } from 'react'
import {
  listDeliveryEvents,
  getInventory,
  requestRestock,
  DeliveryEvent,
  InventoryItem,
} 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 { Truck, AlertTriangle, ArrowRight, RefreshCw, CheckCircle2 } from 'lucide-react'
import { itemStockStatus } from '@/lib/inventory-status'

type RestockState = 'idle' | 'requesting' | 'pending' | 'open' | 'error'

export function StockKeeperJobs() {
  const [pendingDeliveries, setPendingDeliveries] = useState<DeliveryEvent[]>([])
  const [lowStockItems, setLowStockItems] = useState<InventoryItem[]>([])
  const [loading, setLoading] = useState(true)
  const [restock, setRestock] = useState<Record<string, RestockState>>({})

  useEffect(() => {
    let mounted = true
    async function load() {
      try {
        const [delRes, invRes] = await Promise.all([
          listDeliveryEvents({ status: 'dispatched', limit: 5 }),
          getInventory(),
        ])
        if (!mounted) return
        if (delRes.success) setPendingDeliveries(delRes.data.events)
        if (invRes.success) {
          const items = invRes.data.items.filter(
            i => itemStockStatus(i) === 'low_stock' || itemStockStatus(i) === 'out_of_stock'
          ).slice(0, 5)
          setLowStockItems(items)
        }
      } finally {
        if (mounted) setLoading(false)
      }
    }
    load()
    const interval = setInterval(load, 15000)
    return () => { mounted = false; clearInterval(interval) }
  }, [])

  async function handleRestock(productId: string) {
    setRestock(r => ({ ...r, [productId]: 'requesting' }))
    const res = await requestRestock(productId)
    setRestock(r => ({
      ...r,
      [productId]: !res.success
        ? 'error'
        : res.data.reused || res.data.open
          ? 'open'
          : 'pending',
    }))
  }

  if (loading) return null

  const hasJobs = pendingDeliveries.length > 0 || lowStockItems.length > 0
  if (!hasJobs) return null

  return (
    <div className="grid gap-4 sm:grid-cols-2">
      {/* Pending Deliveries */}
      {pendingDeliveries.length > 0 && (
        <Card className="border-amber-200 dark:border-amber-800">
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-amber-800 dark:text-amber-200">
              <Truck className="h-5 w-5" />
              Pending Deliveries
              <Badge variant="warning">{pendingDeliveries.length}</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              These deliveries need stock keeper confirmation:
            </p>
            <ul className="space-y-2">
              {pendingDeliveries.map(d => (
                <li key={d.id} className="flex items-center justify-between text-sm">
                  <span className="font-mono text-gray-500">{d.id.slice(0, 8)}</span>
                  <span className="text-gray-600 dark:text-gray-400">
                    {d.supplier_name || d.supplier_id.slice(0, 8)}
                  </span>
                </li>
              ))}
            </ul>
            <a
              href="/dashboard/inventory"
              className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-amber-700 hover:text-amber-800 dark:text-amber-400 dark:hover:text-amber-300"
            >
              Confirm deliveries <ArrowRight className="h-3.5 w-3.5" />
            </a>
          </CardContent>
        </Card>
      )}

      {/* Low Stock Alerts */}
      {lowStockItems.length > 0 && (
        <Card className="border-red-200 dark:border-red-800">
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-red-800 dark:text-red-200">
              <AlertTriangle className="h-5 w-5" />
              Stock Alerts
              <Badge variant="danger">{lowStockItems.length}</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
              These products need restocking or adjustment:
            </p>
            <ul className="space-y-2">
              {lowStockItems.map(i => {
                const available = Math.max(i.quantity - i.reserved_quantity, 0)
                const pid = i.product_id
                const restockState: RestockState = restock[pid] ?? 'idle'
                return (
                  <li key={i.id} className="flex flex-wrap items-center justify-between gap-2 text-sm">
                    <span className="font-medium text-gray-900 dark:text-white">{i.product?.name}</span>
                    {restockState === 'idle' ? (
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        onClick={() => pid && handleRestock(pid)}
                        className="text-xs"
                      >
                        <RefreshCw className="h-3.5 w-3.5 mr-1" />
                        Request restock
                      </Button>
                    ) : restockState === 'requesting' ? (
                      <Badge variant="info">Requesting…</Badge>
                    ) : restockState === 'open' ? (
                      <Badge variant="warning">Already requested — pending approval</Badge>
                    ) : restockState === 'error' ? (
                      <Badge variant="danger">Could not start restock</Badge>
                    ) : (
                      <Badge variant="success">
                        <CheckCircle2 className="h-3 w-3 mr-1" />
                        Restock pending approval
                      </Badge>
                    )}
                    <Badge variant={available === 0 ? 'danger' : 'warning'}>
                      {available} available
                    </Badge>
                  </li>
                )
              })}
            </ul>
            <a
              href="/dashboard/inventory"
              className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-red-700 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"
            >
              Manage inventory <ArrowRight className="h-3.5 w-3.5" />
            </a>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
