"use client"

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

import { stockTransfersApi } from "@/lib/api/stock-transfers"
import { warehousesApi } from "@/lib/api/warehouses"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { StockTransferSummary } 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 { TransferStatusBadge } from "@/components/stock/status-badges"

export default function TransfersListPage() {
  const [transfers, setTransfers] = useState<StockTransferSummary[] | null>(null)
  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([stockTransfersApi.list({ pageSize: 50 }), warehousesApi.list()])
      .then(([t, wh]) => {
        setTransfers(t.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 Transfers</h1>
            <p className="text-base text-muted-foreground">Move stock between warehouses (FR-STK-05/06).</p>
          </div>
        </div>
        <Link href="/dashboard/stock/transfers/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Transfer
        </Link>
      </div>

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

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

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

      {!error && transfers !== null && transfers.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">From</TableHead>
              <TableHead className="h-12 px-3 text-sm">To</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
              <TableHead className="h-12 px-3 text-sm">Created</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {transfers.map((t) => (
              <TableRow key={t.transferId}>
                <TableCell className="px-3 py-3.5">
                  <Link href={`/dashboard/stock/transfers/${t.transferId}`} className="font-medium text-primary hover:underline">
                    {t.docNo}
                  </Link>
                </TableCell>
                <TableCell className="px-3 py-3.5">{whCode(t.srcWarehouseId)}</TableCell>
                <TableCell className="px-3 py-3.5">{whCode(t.destWarehouseId)}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <TransferStatusBadge status={t.status} />
                </TableCell>
                <TableCell className="px-3 py-3.5">{new Date(t.createdAt).toLocaleString()}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
