"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight, Eye, PackageSearch, Plus, Search } from "lucide-react"

import { grnsApi } from "@/lib/api/grns"
import { errorMessage } from "@/lib/error-map"
import { formatAmount } from "@/lib/format"
import { GrnStatus, GrnSummary } from "@/types/grn"
import { PaginationMeta } from "@/types/common"
import { cn } from "@/lib/utils"
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 { GrnPaymentStatusBadge, GrnStatusBadge } from "@/components/receiving/status-badges"

type StatusFilter = GrnStatus | "All"

const PAGE_SIZE = 5

export default function GrnListPage() {
  const [grns, setGrns] = useState<GrnSummary[] | null>(null)
  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)


  // Debounce the search box so typing doesn't refetch on every keystroke.
  useEffect(() => {
    const timeout = setTimeout(() => setQuery(searchInput.trim()), 300)
    return () => clearTimeout(timeout)
  }, [searchInput])

  // Any filter change starts back at page 1.
  useEffect(() => {
    setPage(1)
  }, [query, status])

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

  useEffect(load, [page, query, status])

  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">Goods Receipt Notes</h1>
          <p className="text-base text-muted-foreground">
            Receive goods against a purchase order, or record a direct receipt.
          </p>
        </div>
        <Link href="/dashboard/receiving/grn/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New GRN
        </Link>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1 basis-0">
          <Search className="pointer-events-none absolute top-1/2 left-4 size-5 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder="Search doc no., PO, vendor, warehouse…"
            className="h-14 w-full pl-11 text-base"
            aria-label="Search GRNs"
          />
        </div>

        <Select value={status} onValueChange={(v) => setStatus(v as StatusFilter)}>
          <SelectTrigger className="h-14! w-full flex-1 basis-0 text-base">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" className="text-base">All statuses</SelectItem>
            <SelectItem value="Draft" className="text-base">Draft</SelectItem>
            <SelectItem value="Confirmed" className="text-base">Confirmed</SelectItem>
            <SelectItem value="Closed" className="text-base">Closed</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 && grns === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && grns !== null && grns.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <PackageSearch className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">
            {hasFilters ? "No GRNs match your search/filter." : "No GRNs yet. Create one from an approved purchase order."}
          </p>
          {hasFilters ? (
            <Button
              type="button"
              variant="outline"
              size="lg"
              onClick={() => {
                setSearchInput("")
                setStatus("All")
              }}
            >
              Clear filters
            </Button>
          ) : (
            <Link href="/dashboard/receiving/grn/new" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
              <Plus className="size-5" />
              New GRN
            </Link>
          )}
        </div>
      )}

      {!error && grns !== null && grns.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">PO</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">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm text-right">Balance</TableHead>
                <TableHead className="h-12 px-3 text-sm">Payment</TableHead>
                <TableHead className="h-12 px-3 text-sm">Created</TableHead>
                <TableHead className="h-12 px-3 text-sm">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {grns.map((grn) => {
                return (
                  <TableRow key={grn.grnId}>
                    <TableCell className="px-3 py-3.5">
                      <Link
                        href={`/dashboard/receiving/grn/${grn.grnId}`}
                        className="font-medium text-foreground hover:underline"
                      >
                        {grn.docNo}
                      </Link>
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{grn.poId ?? <span className="text-muted-foreground">Direct</span>}</TableCell>
                    <TableCell className="px-3 py-3.5">{grn.vendorId}</TableCell>
                    <TableCell className="px-3 py-3.5">{grn.warehouseId}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <GrnStatusBadge status={grn.status} />
                    </TableCell>
                    <TableCell className="px-3 py-3.5 text-right tabular-nums">
                      {grn.status === "Draft" ? "—" : formatAmount(grn.balanceAmount)}
                    </TableCell>
                    <TableCell className="px-3 py-3.5">
                      {grn.status === "Draft" ? (
                        <span className="text-sm text-muted-foreground">—</span>
                      ) : (
                        <GrnPaymentStatusBadge paidAmount={grn.paidAmount} balanceAmount={grn.balanceAmount} />
                      )}
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{new Date(grn.createdAt).toLocaleString()}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <div className="flex items-center gap-1">
                        <Link
                          href={`/dashboard/receiving/grn/${grn.grnId}`}
                          className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }))}
                          aria-label={`View ${grn.docNo}`}
                        >
                          <Eye className="size-4" />
                        </Link>

                        {/* Edit/Delete removed 2026-07-17: the API has no PUT or DELETE for
                            a GRN. A receipt is corrected with a reversing document, never
                            edited or erased (FR-X-05). */}
                      </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>
  )
}
