"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { AlertOctagon, Plus } from "lucide-react"

import { isWastageReasonCode, wastageApi, WastageRecord } from "@/lib/api/wastage"
import { reasonCodesApi } from "@/lib/api/reason-codes"
import { warehousesApi } from "@/lib/api/warehouses"
import { itemsApi } from "@/lib/api/items"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { ReasonCode } from "@/types/stock"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { buttonVariants } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Label } from "@/components/ui/label"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

export default function WastagePage() {
  const [records, setRecords] = useState<WastageRecord[] | null>(null)
  const [reasonCodes, setReasonCodes] = useState<ReasonCode[] | null>(null)
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)

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

  useEffect(() => {
    Promise.all([reasonCodesApi.list("Adjustment"), itemsApi.list({ pageSize: 200 }), warehousesApi.list()])
      .then(([rc, it, wh]) => {
        setReasonCodes(rc.items.filter((r) => isWastageReasonCode(r.code)))
        setItems(it.items)
        setWarehouses(wh.items)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  useEffect(() => {
    wastageApi
      .list({
        warehouseId: warehouseId === "All" ? undefined : warehouseId,
        reasonCodeId: reasonCodeId === "All" ? undefined : reasonCodeId,
      })
      .then(setRecords)
      .catch((err) => setError(errorMessage(err)))
  }, [warehouseId, reasonCodeId])

  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 reasonById = useMemo(() => new Map((reasonCodes ?? []).map((r) => [r.reasonCodeId, r])), [reasonCodes])

  const totals = useMemo(() => {
    if (!records) return { qty: 0, value: 0 }
    return records.reduce(
      (acc, r) => ({ qty: acc.qty + r.qty, value: Math.round((acc.value + r.value) * 100) / 100 }),
      { qty: 0, value: 0 }
    )
  }, [records])

  const loading = !records || !reasonCodes || !items || !warehouses

  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>
            <h1 className="text-2xl font-bold text-foreground">Wastage</h1>
            <p className="text-base text-muted-foreground">
              Damage, theft/loss, and expiry write-offs — posted as reason-coded stock adjustments (FR-STK-07).
            </p>
          </div>
        </div>
        <Link href="/dashboard/stock/wastage/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          Record Wastage
        </Link>
      </div>

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

      {!loading && (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="rounded-xl border border-destructive/20 bg-destructive/5 p-5">
            <p className="text-sm text-muted-foreground">Total quantity wasted</p>
            <p className="text-2xl font-semibold text-destructive">{totals.qty}</p>
          </div>
          <div className="rounded-xl border border-destructive/20 bg-destructive/5 p-5">
            <p className="text-sm text-muted-foreground">Total value wasted (LKR)</p>
            <p className="text-2xl font-semibold text-destructive">{totals.value.toFixed(2)}</p>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <div className="flex flex-col gap-1.5">
          <Label className="text-base">Warehouse</Label>
          <Select<number | "All"> value={warehouseId} onValueChange={(v) => setWarehouseId(v ?? "All")}>
            <SelectTrigger className="h-11! w-full 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>
        <div className="flex flex-col gap-1.5">
          <Label className="text-base">Reason</Label>
          <Select<number | "All"> value={reasonCodeId} onValueChange={(v) => setReasonCodeId(v ?? "All")}>
            <SelectTrigger className="h-11! w-full text-base">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="All" className="text-base">All reasons</SelectItem>
              {(reasonCodes ?? []).map((r) => (
                <SelectItem key={r.reasonCodeId} value={r.reasonCodeId} className="text-base">
                  {r.description}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </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 && records.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <AlertOctagon className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No wastage recorded for this filter.</p>
        </div>
      )}

      {!loading && !error && records.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Date</TableHead>
              <TableHead className="h-12 px-3 text-sm">Doc No</TableHead>
              <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">Reason</TableHead>
              <TableHead className="h-12 px-3 text-sm">Qty wasted</TableHead>
              <TableHead className="h-12 px-3 text-sm">Value (LKR)</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map((r) => {
              const item = itemsById.get(r.itemId)
              const wh = warehousesById.get(r.warehouseId)
              const reason = reasonById.get(r.reasonCodeId)
              return (
                <TableRow key={`${r.adjustmentId}-${r.adjLineId}`}>
                  <TableCell className="px-3 py-3.5">{new Date(r.createdAt).toLocaleString()}</TableCell>
                  <TableCell className="px-3 py-3.5 font-medium">{r.docNo}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <div className="font-medium">{item?.sku ?? `#${r.itemId}`}</div>
                    <div className="text-sm text-muted-foreground">{item?.name}</div>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{wh?.code ?? `#${r.warehouseId}`}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge variant="outline" className="h-6 w-fit justify-center border-transparent bg-destructive/10 px-2.5 text-sm text-destructive">
                      {reason?.description ?? `#${r.reasonCodeId}`}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-3 py-3.5 font-medium text-destructive">-{r.qty}</TableCell>
                  <TableCell className="px-3 py-3.5">{r.value.toFixed(2)}</TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
