"use client"

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

import { stockCountsApi } from "@/lib/api/stock-counts"
import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { StockCountSummary } 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 { CountStatusBadge } from "@/components/stock/status-badges"

export default function CountsListPage() {
  const [counts, setCounts] = useState<StockCountSummary[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([stockCountsApi.list({ pageSize: 50 }), warehousesApi.list()])
      .then(([c, wh]) => {
        setCounts(c.items)
        setWarehouses(wh.items)
      })
      .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 Counts</h1>
            <p className="text-base text-muted-foreground">Cycle or full physical counts (FR-STK-08).</p>
          </div>
        </div>
        <Link href="/dashboard/stock/counts/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Count
        </Link>
      </div>

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

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

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

      {!error && counts !== null && counts.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">Type</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Created</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {counts.map((c) => (
              <TableRow key={c.countId}>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/stock/counts/${c.countId}`} className="font-medium text-primary hover:underline">
                    {c.docNo}
                  </Link>
                </TableCell>
                <TableCell className="px-3 py-3.5">{whCode(c.warehouseId)}</TableCell>
                <TableCell className="px-3 py-3.5">{c.countType}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <CountStatusBadge status={c.status} />
                </TableCell>
                <TableCell className="px-3 py-3.5">{new Date(c.createdAt).toLocaleString()}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
