"use client"

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

import { purchaseReturnsApi } from "@/lib/api/purchase-returns"
import { vendorsApi } from "@/lib/api/vendors"
import { warehousesApi } from "@/lib/api/warehouses"
import { reasonCodesApi } from "@/lib/api/reason-codes"
import { errorMessage } from "@/lib/error-map"
import { PurchaseReturnSummary } from "@/types/procurement"
import { Vendor, Warehouse } from "@/types/master-data"
import { ReasonCode } from "@/types/stock"
import { cn } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { buttonVariants } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

export default function PurchaseReturnsListPage() {
  const [returns, setReturns] = useState<PurchaseReturnSummary[] | null>(null)
  const [vendors, setVendors] = useState<Vendor[]>([])
  const [warehouses, setWarehouses] = useState<Warehouse[]>([])
  const [reasonCodes, setReasonCodes] = useState<ReasonCode[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([purchaseReturnsApi.list(), vendorsApi.list({ pageSize: 200 }), warehousesApi.list(), reasonCodesApi.list("Return")])
      .then(([r, v, w, rc]) => {
        setReturns(r.items)
        setVendors(v.items)
        setWarehouses(w.items)
        setReasonCodes(rc.items)
      })
      .catch((err) => setError(errorMessage(err)))
  }, [])

  function vendorCode(id: number) {
    return vendors.find((v) => v.vendorId === id)?.code ?? `#${id}`
  }
  function warehouseCode(id: number) {
    return warehouses.find((w) => w.warehouseId === id)?.code ?? `#${id}`
  }
  function reasonLabel(id: number) {
    return reasonCodes.find((r) => r.reasonCodeId === id)?.description ?? `#${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>
          <h1 className="text-2xl font-bold text-foreground">Purchase Returns</h1>
          <p className="text-base text-muted-foreground">Return received goods to a vendor, referencing the original GRN line (FR-PROC-08).</p>
        </div>
        <Link href="/dashboard/procurement/purchase-returns/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Return
        </Link>
      </div>

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

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

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

      {!error && returns !== null && returns.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">Vendor</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>
            {returns.map((r) => (
              <TableRow key={r.returnId}>
                <TableCell className="px-3 py-3.5 font-medium">{r.docNo}</TableCell>
                <TableCell className="px-3 py-3.5">{vendorCode(r.vendorId)}</TableCell>
                <TableCell className="px-3 py-3.5">{warehouseCode(r.warehouseId)}</TableCell>
                <TableCell className="px-3 py-3.5">{reasonLabel(r.reasonCodeId)}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge variant="outline" className="h-6 w-fit justify-center border-transparent bg-success/10 px-2.5 text-sm text-success">
                    {r.status}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-3.5 text-muted-foreground">{r.glJournalNo ?? "—"}</TableCell>
                <TableCell className="px-3 py-3.5">{new Date(r.createdAt).toLocaleString()}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
