"use client"

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

import { requisitionsApi } from "@/lib/api/requisitions"
import { errorMessage } from "@/lib/error-map"
import { RequisitionStatus, RequisitionSummary } from "@/types/procurement"
import { PaginationMeta } from "@/types/common"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
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 { RequisitionStatusBadge } from "@/components/procurement/status-badges"

type StatusFilter = RequisitionStatus | "All"

const PAGE_SIZE = 10

export default function RequisitionsListPage() {
  const [requisitions, setRequisitions] = useState<RequisitionSummary[] | null>(null)
  const [pagination, setPagination] = useState<PaginationMeta | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [status, setStatus] = useState<StatusFilter>("All")
  const [page, setPage] = useState(1)

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

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

  useEffect(load, [page, status])

  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">Requisitions</h1>
          <p className="text-base text-muted-foreground">Raise a purchase requisition and submit it into procurement (FR-PROC-01).</p>
        </div>
        <Link href="/dashboard/procurement/requisitions/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Requisition
        </Link>
      </div>

      <div className="flex items-center gap-3">
        <Select value={status} onValueChange={(v) => setStatus(v as StatusFilter)}>
          <SelectTrigger className="h-12! 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="Submitted" className="text-base">Submitted</SelectItem>
          </SelectContent>
        </Select>
      </div>

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

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

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

      {!error && requisitions !== null && requisitions.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">Status</TableHead>
                <TableHead className="h-12 px-3 text-sm">Lines</TableHead>
                <TableHead className="h-12 px-3 text-sm">Requested by</TableHead>
                <TableHead className="h-12 px-3 text-sm">Created</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {requisitions.map((r) => (
                <TableRow key={r.requisitionId}>
                  <TableCell className="px-3 py-3.5">
                    <Link href={`/dashboard/procurement/requisitions/${r.requisitionId}`} className="font-medium text-foreground hover:underline">
                      {r.docNo}
                    </Link>
                  </TableCell>
                  <TableCell className="px-3 py-3.5">
                    <RequisitionStatusBadge status={r.status} />
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{r.lineCount}</TableCell>
                  <TableCell className="px-3 py-3.5">#{r.requestedBy}</TableCell>
                  <TableCell className="px-3 py-3.5">{new Date(r.createdAt).toLocaleString()}</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))}>
                  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
                </Button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
