"use client"

import { Suspense, useEffect, useMemo, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { BadgeDollarSign } 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 { Valuation } from "@/types/stock"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { Label } from "@/components/ui/label"
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"

function ValuationContent() {
  const router = useRouter()
  const searchParams = useSearchParams()

  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [valuation, setValuation] = useState<Valuation | null>(null)
  const [error, setError] = useState<string | null>(null)

  const itemId = Number(searchParams.get("itemId")) || null
  const warehouseId = Number(searchParams.get("warehouseId")) || null

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

  useEffect(() => {
    if (!itemId || !warehouseId) {
      setValuation(null)
      return
    }
    setError(null)
    stockApi
      .valuation(itemId, warehouseId)
      .then(setValuation)
      .catch((err) => setError(errorMessage(err)))
  }, [itemId, warehouseId])

  const item = useMemo(() => (items ?? []).find((i) => i.itemId === itemId), [items, itemId])

  function setParam(key: "itemId" | "warehouseId", value: number) {
    const params = new URLSearchParams(searchParams.toString())
    params.set(key, String(value))
    router.push(`/dashboard/stock/valuation?${params.toString()}`)
  }

  const loading = 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">Valuation</h1>
          <p className="text-base text-muted-foreground">FIFO cost-layer breakdown and total stock value (FR-STK-04).</p>
        </div>
      </div>

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

      {loading ? (
        <Skeleton className="h-12 w-full" />
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="flex flex-col gap-1.5">
            <Label className="text-base">Item</Label>
            <Select<number | null> value={itemId} onValueChange={(v) => v && setParam("itemId", v)}>
              <SelectTrigger className="h-12! w-full text-base">
                <SelectValue placeholder="Select an item" />
              </SelectTrigger>
              <SelectContent>
                {(items ?? []).map((i) => (
                  <SelectItem key={i.itemId} value={i.itemId} className="text-base">
                    {i.sku} — {i.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex flex-col gap-1.5">
            <Label className="text-base">Warehouse</Label>
            <Select<number | null> value={warehouseId} onValueChange={(v) => v && setParam("warehouseId", v)}>
              <SelectTrigger className="h-12! w-full text-base">
                <SelectValue placeholder="Select a warehouse" />
              </SelectTrigger>
              <SelectContent>
                {(warehouses ?? []).map((w) => (
                  <SelectItem key={w.warehouseId} value={w.warehouseId} className="text-base">
                    {w.code} — {w.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      )}

      {!itemId || !warehouseId ? (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <BadgeDollarSign className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">Select an item and warehouse to see its FIFO valuation.</p>
        </div>
      ) : valuation === null ? (
        <Skeleton className="h-48 w-full" />
      ) : (
        <>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
            <div className="rounded-xl border p-5">
              <p className="text-sm text-muted-foreground">Item</p>
              <p className="text-lg font-semibold">{item?.sku ?? `#${itemId}`}</p>
            </div>
            <div className="rounded-xl border p-5">
              <p className="text-sm text-muted-foreground">Total quantity</p>
              <p className="text-lg font-semibold">{valuation.totalQty}</p>
            </div>
            <div className="rounded-xl border p-5">
              <p className="text-sm text-muted-foreground">Total value ({valuation.currency})</p>
              <p className="text-lg font-semibold">{valuation.totalValue.toFixed(2)}</p>
            </div>
          </div>

          {valuation.layers.length === 0 ? (
            <p className="text-base text-muted-foreground">No open FIFO layers for this item/warehouse.</p>
          ) : (
            <Table className="text-base">
              <TableHeader>
                <TableRow>
                  <TableHead className="h-12 px-3 text-sm">Layer</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Receipt date</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Qty remaining</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Unit cost</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Value</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {valuation.layers.map((layer) => (
                  <TableRow key={layer.layerId}>
                    <TableCell className="px-3 py-3.5">#{layer.layerId}</TableCell>
                    <TableCell className="px-3 py-3.5">{new Date(layer.receiptDate).toLocaleString()}</TableCell>
                    <TableCell className="px-3 py-3.5">{layer.qtyRemaining}</TableCell>
                    <TableCell className="px-3 py-3.5">{layer.unitCost.toFixed(2)}</TableCell>
                    <TableCell className="px-3 py-3.5">{layer.value.toFixed(2)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </>
      )}
    </div>
  )
}

export default function StockValuationPage() {
  return (
    <Suspense fallback={<Skeleton className="h-48 w-full" />}>
      <ValuationContent />
    </Suspense>
  )
}
