"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { PackageSearch, Search } 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 { OnHand } from "@/types/stock"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

export default function StockEnquiryPage() {
  const [rows, setRows] = useState<OnHand[] | null>(null)
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [search, setSearch] = useState("")
  const [warehouseId, setWarehouseId] = useState<number | "All">("All")

  useEffect(() => {
    Promise.all([stockApi.onHandList({ pageSize: 200 }), itemsApi.list({ pageSize: 200 }), warehousesApi.list()])
      .then(([r, it, wh]) => {
        setRows(r.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])

  const filtered = useMemo(() => {
    if (!rows) return null
    const term = search.trim().toLowerCase()
    return rows
      .filter((r) => warehouseId === "All" || r.warehouseId === warehouseId)
      .filter((r) => {
        if (!term) return true
        const item = itemsById.get(r.itemId)
        const haystack = `${item?.sku ?? ""} ${item?.name ?? ""}`.toLowerCase()
        return haystack.includes(term)
      })
      .sort((a, b) => a.itemId - b.itemId || a.warehouseId - b.warehouseId)
  }, [rows, search, warehouseId, itemsById])

  const loading = rows === null || items === null || warehouses === null

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Stock Enquiry</h1>
          <p className="text-base text-muted-foreground">On-hand, available, on-hold, and in-transit by item and warehouse (FR-STK-12).</p>
        </div>
      </div>

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

      {!error && (
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="relative flex-1 basis-0">
            <Search className="pointer-events-none absolute top-1/2 left-4 size-5 -translate-y-1/2 text-muted-foreground" />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by SKU or item name…"
              className="h-14 w-full pl-11 text-base"
              aria-label="Search items"
            />
          </div>
          <Select<number | "All"> value={warehouseId} onValueChange={(v) => setWarehouseId(v ?? "All")}>
            <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="All" className="text-base">All warehouses</SelectItem>
              {(warehouses ?? []).map((w) => (
                <SelectItem key={w.warehouseId} value={w.warehouseId} className="text-base">
                  {w.code} — {w.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

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

      {!loading && !error && filtered !== null && filtered.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <PackageSearch className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No stock matches your search/filter.</p>
        </div>
      )}

      {!loading && !error && filtered !== null && filtered.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">On hand</TableHead>
              <TableHead className="h-12 px-3 text-sm">Available</TableHead>
              <TableHead className="h-12 px-3 text-sm">On hold</TableHead>
              <TableHead className="h-12 px-3 text-sm">In transit</TableHead>
              <TableHead className="h-12 px-3 text-sm">Reserved</TableHead>
              <TableHead className="h-12 px-3 text-sm">Valuation</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.map((row) => {
              const item = itemsById.get(row.itemId)
              const wh = warehousesById.get(row.warehouseId)
              return (
                <TableRow key={`${row.itemId}-${row.warehouseId}`}>
                  <TableCell className="px-3 py-3.5">
                    <div className="font-medium">{item?.sku ?? `#${row.itemId}`}</div>
                    <div className="text-sm text-muted-foreground">{item?.name}</div>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{wh?.code ?? `#${row.warehouseId}`}</TableCell>
                  <TableCell className="px-3 py-3.5">{row.onHand}</TableCell>
                  <TableCell className="px-3 py-3.5 font-medium">{row.available}</TableCell>
                  <TableCell className="px-3 py-3.5">{row.onHold}</TableCell>
                  <TableCell className="px-3 py-3.5">{row.inTransit}</TableCell>
                  <TableCell className="px-3 py-3.5">{row.reserved}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Link
                      href={`/dashboard/stock/valuation?itemId=${row.itemId}&warehouseId=${row.warehouseId}`}
                      className="font-medium text-primary hover:underline"
                    >
                      View
                    </Link>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
