"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Check, ChevronLeft, ChevronRight, Eye, Pencil, Plus, ShoppingCart, Trash2 } from "lucide-react"

import { isPoEditable, purchaseOrdersApi } from "@/lib/api/purchase-orders"
import { vendorsApi } from "@/lib/api/vendors"
import { errorMessage } from "@/lib/error-map"
import { PurchaseOrderStatus, PurchaseOrderSummary } from "@/types/procurement"
import { Vendor } from "@/types/master-data"
import { PaginationMeta } from "@/types/common"
import { cn } from "@/lib/utils"
import { AlertDialog, AlertDialogContent, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Button, buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { toast } from "@/components/ui/toast"
import { PoStatusBadge } from "@/components/procurement/status-badges"

type StatusFilter = PurchaseOrderStatus | "All"

const PAGE_SIZE = 10

export default function PurchaseOrdersListPage() {
  const [pos, setPos] = useState<PurchaseOrderSummary[] | null>(null)
  const [vendors, setVendors] = useState<Vendor[]>([])
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)

  const [searchInput, setSearchInput] = useState("")
  const [query, setQuery] = useState("")
  const [status, setStatus] = useState<StatusFilter>("All")
  const [page, setPage] = useState(1)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [approvingId, setApprovingId] = useState<number | null>(null)

  useEffect(() => {
    const timeout = setTimeout(() => setQuery(searchInput.trim()), 300)
    return () => clearTimeout(timeout)
  }, [searchInput])

  useEffect(() => setPage(1), [query, status])

  function load() {
    setError(null)
    purchaseOrdersApi
      .list({ page, pageSize: PAGE_SIZE, q: query || undefined, status: status === "All" ? undefined : status })
      .then((res) => {
        setPos(res.items)
        setPagination(res.pagination)
      })
      .catch((err) => setError(errorMessage(err)))
  }

  useEffect(load, [page, query, status])
  useEffect(() => {
    vendorsApi.list({ pageSize: 200 }).then((res) => setVendors(res.items)).catch(() => {})
  }, [])

  function vendorCode(vendorId: number) {
    return vendors.find((v) => v.vendorId === vendorId)?.code ?? `#${vendorId}`
  }

  async function handleDelete(po: PurchaseOrderSummary) {
    setDeletingId(po.poId)
    try {
      await purchaseOrdersApi.remove(po.poId)
      toast.success("Draft deleted", po.docNo)
      load()
    } catch (err) {
      toast.error("Could not delete purchase order", errorMessage(err))
    } finally {
      setDeletingId(null)
    }
  }

  async function handleApprove(po: PurchaseOrderSummary) {
    setApprovingId(po.poId)
    try {
      const updated = await purchaseOrdersApi.submit(po.poId)
      toast.success("Purchase order approved", `${updated.docNo} — now ${updated.status}.`)
      load()
    } catch (err) {
      toast.error("Could not approve purchase order", errorMessage(err))
    } finally {
      setApprovingId(null)
    }
  }

  const hasFilters = query.length > 0 || status !== "All"

  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 Orders</h1>
          <p className="text-base text-muted-foreground">Auto-approved on creation and freely editable while open (FR-PROC-03..05).</p>
        </div>
        <Link href="/dashboard/procurement/purchase-orders/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New PO
        </Link>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <Input
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          placeholder="Search doc no., vendor…"
          className="h-12 w-full flex-1 basis-0 text-base"
          aria-label="Search purchase orders"
        />
        <Select value={status} onValueChange={(v) => setStatus(v as StatusFilter)}>
          <SelectTrigger className="h-12! w-full sm:w-56 text-base">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" className="text-base">All statuses</SelectItem>
            <SelectItem value="Draft" className="text-base">Draft</SelectItem>
            <SelectItem value="Approved" className="text-base">Approved</SelectItem>
            <SelectItem value="PartiallyReceived" className="text-base">Partially received</SelectItem>
            <SelectItem value="FullyReceived" className="text-base">Fully received</SelectItem>
            <SelectItem value="Closed" className="text-base">Closed</SelectItem>
            <SelectItem value="Cancelled" className="text-base">Cancelled</SelectItem>
          </SelectContent>
        </Select>
        {hasFilters && (
          <Button type="button" variant="ghost" onClick={() => { setSearchInput(""); setStatus("All") }}>
            Clear filters
          </Button>
        )}
      </div>

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

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

      {!error && pos !== null && pos.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <ShoppingCart className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">{hasFilters ? "No purchase orders match your search/filter." : "No purchase orders yet."}</p>
        </div>
      )}

      {!error && pos !== null && pos.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">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm">Grand total</TableHead>
                <TableHead className="h-12 px-3 text-sm">Created</TableHead>
                <TableHead className="h-12 w-44 px-3 text-sm">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {pos.map((po) => {
                const editable = isPoEditable(po.status)
                return (
                  <TableRow key={po.poId}>
                    <TableCell className="px-3 py-3.5">
                      <Link href={`/dashboard/procurement/purchase-orders/${po.poId}`} className="font-medium text-foreground hover:underline">
                        {po.docNo}
                      </Link>
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{vendorCode(po.vendorId)}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <PoStatusBadge status={po.status} />
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{po.totals.currency} {po.totals.grandTotal.toFixed(2)}</TableCell>
                    <TableCell className="px-3 py-3.5">{new Date(po.createdAt).toLocaleString()}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <div className="flex items-center gap-1">
                        <Link
                          href={`/dashboard/procurement/purchase-orders/${po.poId}`}
                          className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}
                          aria-label="View"
                          title="View"
                        >
                          <Eye className="size-4" />
                        </Link>
                        {editable && (
                          <>
                            <Link
                              href={`/dashboard/procurement/purchase-orders/${po.poId}`}
                              className={cn(buttonVariants({ variant: "ghost", size: "icon" }))}
                              aria-label="Edit draft"
                              title="Edit draft"
                            >
                              <Pencil className="size-4" />
                            </Link>
                            <AlertDialog>
                              <AlertDialogTrigger
                                render={
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    aria-label="Approve draft"
                                    title="Approve draft"
                                    disabled={approvingId === po.poId || deletingId === po.poId}
                                    className="text-success hover:bg-success/10 hover:text-success"
                                  />
                                }
                              >
                                <Check className="size-4" />
                              </AlertDialogTrigger>
                              <AlertDialogContent
                                variant="success"
                                title={`Approve ${po.docNo}?`}
                                description="It will be locked for editing once approved."
                                confirmLabel="Approve"
                                onConfirm={() => handleApprove(po)}
                              />
                            </AlertDialog>
                            <AlertDialog>
                              <AlertDialogTrigger
                                render={
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    aria-label="Delete draft"
                                    title="Delete draft"
                                    disabled={deletingId === po.poId || approvingId === po.poId}
                                    className="text-destructive hover:bg-destructive/10 hover:text-destructive"
                                  />
                                }
                              >
                                <Trash2 className="size-4" />
                              </AlertDialogTrigger>
                              <AlertDialogContent
                                variant="destructive"
                                title={`Delete draft ${po.docNo}?`}
                                description="This cannot be undone."
                                confirmLabel="Delete"
                                onConfirm={() => handleDelete(po)}
                              />
                            </AlertDialog>
                          </>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>

          {pagination && pagination.totalPages > 1 && (
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                Showing {(pagination.page - 1) * pagination.pageSize + 1}–
                {Math.min(pagination.page * pagination.pageSize, pagination.totalItems)} of {pagination.totalItems}
              </p>
              <div className="flex items-center gap-2">
                <Button type="button" variant="outline" size="sm" disabled={pagination.page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>
                  <ChevronLeft />
                  Previous
                </Button>
                <span className="text-sm text-muted-foreground">Page {pagination.page} of {pagination.totalPages}</span>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={pagination.page >= pagination.totalPages}
                  onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}
                >
                  Next
                  <ChevronRight />
                </Button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
