"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { CheckCircle2, PackageCheck, Truck } from "lucide-react"

import { stockTransfersApi } from "@/lib/api/stock-transfers"
import { errorMessage } from "@/lib/error-map"
import { DispatchTransferResponse, ReceiveTransferResponse, StockTransfer } from "@/types/stock"

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

export default function TransferDetailPage() {
  const params = useParams<{ id: string }>()
  const transferId = Number(params.id)

  const [transfer, setTransfer] = useState<StockTransfer | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [dispatching, setDispatching] = useState(false)
  const [receiving, setReceiving] = useState(false)
  const [dispatchResult, setDispatchResult] = useState<DispatchTransferResponse | null>(null)
  const [receiveResult, setReceiveResult] = useState<ReceiveTransferResponse | null>(null)

  useEffect(() => {
    if (!Number.isFinite(transferId)) return
    stockTransfersApi.get(transferId).then(setTransfer).catch((err) => setError(errorMessage(err)))
  }, [transferId])

  async function handleDispatch() {
    setError(null)
    setDispatching(true)
    try {
      const result = await stockTransfersApi.dispatch(transferId)
      setDispatchResult(result)
      setTransfer((prev) => (prev ? { ...prev, status: result.status } : prev))
      toast.success("Transfer dispatched", `${result.consumedLayers.length} layer(s) consumed at source.`)
    } catch (err) {
      setError(errorMessage(err))
      toast.error("Could not dispatch transfer", errorMessage(err))
    } finally {
      setDispatching(false)
    }
  }

  async function handleReceive() {
    if (!transfer) return
    setError(null)
    setReceiving(true)
    try {
      const result = await stockTransfersApi.receive(
        transferId,
        transfer.lines.map((l) => ({ transferLineId: l.transferLineId, qty: l.qty }))
      )
      setReceiveResult(result)
      setTransfer((prev) => (prev ? { ...prev, status: result.status } : prev))
      toast.success("Transfer received", `${result.createdLayers.length} layer(s) created at destination.`)
    } catch (err) {
      setError(errorMessage(err))
      toast.error("Could not receive transfer", errorMessage(err))
    } finally {
      setReceiving(false)
    }
  }

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

  if (!transfer) {
    return (
      <div className="flex flex-col gap-3">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  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>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-foreground">{transfer.docNo}</h1>
              <TransferStatusBadge status={transfer.status} />
            </div>
            <p className="text-base text-muted-foreground">
              Warehouse #{transfer.srcWarehouseId} → Warehouse #{transfer.destWarehouseId}
            </p>
          </div>
        </div>

        <div className="flex gap-3">
          {transfer.status === "Draft" && (
            <Button size="lg" onClick={handleDispatch} disabled={dispatching}>
              <Truck className="size-5" />
              {dispatching ? "Dispatching…" : "Dispatch"}
            </Button>
          )}
          {transfer.status === "InTransit" && (
            <Button size="lg" onClick={handleReceive} disabled={receiving}>
              <PackageCheck className="size-5" />
              {receiving ? "Receiving…" : "Receive"}
            </Button>
          )}
        </div>
      </div>

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

      {dispatchResult && (
        <div className="flex flex-col gap-2 rounded-xl border border-success/30 bg-success/5 p-5">
          <div className="flex items-center gap-2 text-success">
            <CheckCircle2 className="size-6" />
            <p className="text-base font-semibold">Dispatched — source layers consumed (cost-preserving, FR-STK-06)</p>
          </div>
          <div className="text-sm text-muted-foreground">
            Consumed: {dispatchResult.consumedLayers.map((l) => `#${l.layerId} (${l.qtyConsumed} @ ${l.unitCost})`).join(", ")}
          </div>
          <div className="text-sm text-muted-foreground">Ledger refs: {dispatchResult.ledgerRefs.join(", ")}</div>
        </div>
      )}

      {receiveResult && (
        <div className="flex flex-col gap-2 rounded-xl border border-success/30 bg-success/5 p-5">
          <div className="flex items-center gap-2 text-success">
            <CheckCircle2 className="size-6" />
            <p className="text-base font-semibold">Received — destination layers created</p>
          </div>
          <div className="text-sm text-muted-foreground">
            Created: {receiveResult.createdLayers.map((l) => `#${l.layerId} (${l.qtyReceived} @ ${l.unitCost})`).join(", ")}
          </div>
          <div className="text-sm text-muted-foreground">Ledger refs: {receiveResult.ledgerRefs.join(", ")}</div>
        </div>
      )}

      <Table className="text-base">
        <TableHeader>
          <TableRow>
            <TableHead className="h-12 px-3 text-sm">Item</TableHead>
            <TableHead className="h-12 px-3 text-sm">Src bin</TableHead>
            <TableHead className="h-12 px-3 text-sm">Dest bin</TableHead>
            <TableHead className="h-12 px-3 text-sm">Qty</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {transfer.lines.map((line) => (
            <TableRow key={line.transferLineId}>
              <TableCell className="px-3 py-3.5">#{line.itemId}</TableCell>
              <TableCell className="px-3 py-3.5">{line.srcBinId ?? "—"}</TableCell>
              <TableCell className="px-3 py-3.5">{line.destBinId ?? "—"}</TableCell>
              <TableCell className="px-3 py-3.5">{line.qty}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
