"use client"

import { useEffect, useMemo, useState } from "react"
import { AlertTriangle, CheckCircle2 } from "lucide-react"

import { stockApi } from "@/lib/api/stock"
import { itemsApi } from "@/lib/api/items"
import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } from "@/lib/error-map"
import { ReorderAlert } from "@/types/stock"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { Button } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"

export default function ReorderAlertsPage() {
  const [alerts, setAlerts] = useState<ReorderAlert[] | null>(null)
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [requesting, setRequesting] = useState<string | null>(null)
  const [requested, setRequested] = useState<Set<string>>(new Set())

  useEffect(() => {
    Promise.all([stockApi.reorderAlerts(), itemsApi.list({ pageSize: 200 }), warehousesApi.list()])
      .then(([a, it, wh]) => {
        setAlerts(a.items)
        setItems(it.items)
        setWarehouses(wh.items)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  const itemsById = useMemo(() => new Map((items ?? []).map((i) => [i.itemId, i])), [items])
  const warehousesById = useMemo(() => new Map((warehouses ?? []).map((w) => [w.warehouseId, w])), [warehouses])

  async function handleRequisition(alert: ReorderAlert) {
    const key = `${alert.itemId}-${alert.warehouseId}`
    setRequesting(key)
    try {
      // The server returns the full requisition; the suggested qty is on its line.
      const res = await stockApi.createReorderRequisition(alert.itemId, alert.warehouseId)
      setRequested((prev) => new Set(prev).add(key))
      const qty = res.lines[0]?.qty ?? alert.suggestedRequisitionQty
      toast.success("Requisition created", `${res.docNo} for ${qty} units.`)
    } catch (err) {
      toast.error("Could not create requisition", errorMessage(err))
    } finally {
      setRequesting(null)
    }
  }

  const loading = !alerts || !items || !warehouses

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Reorder Alerts</h1>
          <p className="text-base text-muted-foreground">Items at or below their reorder point (FR-STK-10).</p>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
      )}

      {loading && !error && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!loading && !error && alerts.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <CheckCircle2 className="size-12 text-success" />
          <p className="text-base text-muted-foreground">Nothing is below its reorder point right now.</p>
        </div>
      )}

      {!loading && !error && alerts.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Item</TableHead>
              <TableHead className="h-12 px-3 text-sm">Warehouse</TableHead>
              <TableHead className="h-12 px-3 text-sm">Available</TableHead>
              <TableHead className="h-12 px-3 text-sm">Reorder point</TableHead>
              <TableHead className="h-12 px-3 text-sm">Suggested qty</TableHead>
              <TableHead className="h-12 px-3 text-sm">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {alerts.map((alert) => {
              const key = `${alert.itemId}-${alert.warehouseId}`
              const item = itemsById.get(alert.itemId)
              const wh = warehousesById.get(alert.warehouseId)
              const done = requested.has(key)
              return (
                <TableRow key={key}>
                  <TableCell className="px-3 py-3.5">
                    <div className="flex items-center gap-2">
                      <AlertTriangle className="size-4 text-warning" />
                      <div>
                        <div className="font-medium">{item?.sku ?? `#${alert.itemId}`}</div>
                        <div className="text-sm text-muted-foreground">{item?.name}</div>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{wh?.code ?? `#${alert.warehouseId}`}</TableCell>
                  <TableCell className="px-3 py-3.5 font-medium text-destructive">{alert.available}</TableCell>
                  <TableCell className="px-3 py-3.5">{alert.reorderPoint}</TableCell>
                  <TableCell className="px-3 py-3.5">{alert.suggestedRequisitionQty}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Button
                      type="button"
                      size="sm"
                      variant={done ? "outline" : "default"}
                      disabled={done || requesting === key}
                      onClick={() => handleRequisition(alert)}
                    >
                      {done ? "Requisitioned" : requesting === key ? "Creating…" : "Create requisition"}
                    </Button>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
