"use client"

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

import { stockAdjustmentsApi } from "@/lib/api/stock-adjustments"
import { warehousesApi } from "@/lib/api/warehouses"
import { reasonCodesApi } from "@/lib/api/reason-codes"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { StockAdjustmentSummary } from "@/types/stock"
import { Warehouse } from "@/types/master-data"

import { buttonVariants } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { AdjustmentStatusBadge } from "@/components/stock/status-badges"

export default function AdjustmentsListPage() {
  const [adjustments, setAdjustments] = useState<StockAdjustmentSummary[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [reasonLabels, setReasonLabels] = useState<Map<number, string>>(new Map())
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([stockAdjustmentsApi.list({ pageSize: 50 }), warehousesApi.list(), reasonCodesApi.list("Adjustment")])
      .then(([a, wh, rc]) => {
        setAdjustments(a.items)
        setWarehouses(wh.items)
        setReasonLabels(new Map(rc.items.map((r) => [r.reasonCodeId, r.description])))
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  const whCode = (id: number) => warehouses?.find((w) => w.warehouseId === id)?.code ?? `#${id}`

  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">Stock Adjustments</h1>
            <p className="text-base text-muted-foreground">Increase, decrease, or write off stock with a reason code (FR-STK-07).</p>
          </div>
        </div>
        <Link href="/dashboard/stock/adjustments/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Adjustment
        </Link>
      </div>

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

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

      {!error && adjustments !== null && adjustments.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <SlidersHorizontal className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No adjustments yet.</p>
          <Link href="/dashboard/stock/adjustments/new" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
            <Plus className="size-5" />
            New Adjustment
          </Link>
        </div>
      )}

      {!error && adjustments !== null && adjustments.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Doc No</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">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">GL Journal</TableHead>
              <TableHead className="h-12 px-3 text-sm">Created</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {adjustments.map((a) => (
              <TableRow key={a.adjustmentId}>
                <TableCell className="px-3 py-3.5 font-medium">{a.docNo}</TableCell>
                <TableCell className="px-3 py-3.5">{whCode(a.warehouseId)}</TableCell>
                <TableCell className="px-3 py-3.5">{reasonLabels.get(a.reasonCodeId) ?? `#${a.reasonCodeId}`}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <AdjustmentStatusBadge status={a.status} />
                </TableCell>
                <TableCell className="px-3 py-3.5 text-muted-foreground">{a.glJournalNo ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">{new Date(a.createdAt).toLocaleString()}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
