"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import Link from "next/link"
import { FileText, Send, ShoppingCart } from "lucide-react"

import { requisitionsApi } from "@/lib/api/requisitions"
import { itemsApi } from "@/lib/api/items"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { Requisition } from "@/types/procurement"
import { ItemListItem } from "@/types/master-data"

import { Button, buttonVariants } 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"
import { RequisitionStatusBadge } from "@/components/procurement/status-badges"

export default function RequisitionDetailPage() {
  const params = useParams<{ id: string }>()
  const requisitionId = Number(params.id)

  const [requisition, setRequisition] = useState<Requisition | null>(null)
  const [items, setItems] = useState<ItemListItem[]>([])
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  function load() {
    setError(null)
    requisitionsApi.get(requisitionId).then(setRequisition).catch((err) => setError(errorMessage(err)))
  }

  useEffect(() => {
    if (!Number.isFinite(requisitionId)) return
    load()
    itemsApi.list({ pageSize: 200 }).then((res) => setItems(res.items)).catch(() => {})
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [requisitionId])

  function itemFor(itemId: number) {
    return items.find((i) => i.itemId === itemId)
  }

  async function handleSubmit() {
    if (!requisition) return
    setSubmitting(true)
    try {
      const updated = await requisitionsApi.submit(requisition.requisitionId)
      setRequisition(updated)
      toast.success("Requisition submitted", `${updated.docNo} is ready for RFQ or a direct PO.`)
    } catch (err) {
      toast.error("Could not submit requisition", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

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

  if (!requisition) {
    return (
      <div className="flex flex-col gap-3">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-foreground">{requisition.docNo}</h1>
              <RequisitionStatusBadge status={requisition.status} />
            </div>
            <p className="text-base text-muted-foreground">Requested by #{requisition.requestedBy} — {new Date(requisition.createdAt).toLocaleString()}</p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          {requisition.status === "Draft" && (
            <Button size="lg" onClick={handleSubmit} disabled={submitting}>
              <Send className="size-5" />
              {submitting ? "Submitting…" : "Submit"}
            </Button>
          )}
          {requisition.status === "Submitted" && (
            <>
              <Link
                href={`/dashboard/procurement/rfqs/new?requisitionId=${requisition.requisitionId}`}
                className={cn(buttonVariants({ variant: "outline", size: "lg" }))}
              >
                <FileText className="size-5" />
                Create RFQ
              </Link>
              <Link
                href={`/dashboard/procurement/purchase-orders/new?requisitionId=${requisition.requisitionId}`}
                className={cn(buttonVariants({ size: "lg" }))}
              >
                <ShoppingCart className="size-5" />
                Create PO
              </Link>
            </>
          )}
        </div>
      </div>

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

      <Table className="text-base">
        <TableHeader>
          <TableRow>
            <TableHead className="h-12 px-3 text-sm">Item</TableHead>
            <TableHead className="h-12 px-3 text-sm">Qty</TableHead>
            <TableHead className="h-12 px-3 text-sm">Required by</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {requisition.lines.map((line) => {
            const item = itemFor(line.itemId)
            return (
              <TableRow key={line.reqLineId}>
                <TableCell className="px-3 py-3.5">{item ? `${item.sku} — ${item.name}` : `Item #${line.itemId}`}</TableCell>
                <TableCell className="px-3 py-3.5">{line.qty}</TableCell>
                <TableCell className="px-3 py-3.5">{line.requiredBy}</TableCell>
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
