﻿"use client";

import Link from "next/link";
import { useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ClipboardListIcon, DollarSignIcon, FileTextIcon, SearchIcon } from "@/components/dashboard-icons";
import {
  formatPurchaseRequestMoney,
  formatPurchaseRequestStatus,
  getPurchaseRequestStatusClass,
  purchaseRequestRows,
} from "@/lib/purchase-request-data";
import { getVendorPoByPurchaseRequestId } from "@/lib/vendor-po-data";
import { getLockedRapWorkspaces, getRapStatusClass, getRapStatusLabel } from "@/lib/customer-po-rap-data";
import { cn } from "@/lib/utils";
import { Pagination } from "@/components/ui/pagination";

function Badge({ label, className }: { label: string; className: string }) {
  return <span className={cn("inline-flex rounded-full px-2.5 py-1 text-xs font-semibold", className)}>{label}</span>;
}

export function PurchaseRequestQueueWorkspace() {
  const lockedRapWorkspaces = getLockedRapWorkspaces();

  const [page, setPage] = useState(1);
  const pageSize = 5;
  const totalPages = Math.ceil(purchaseRequestRows.length / pageSize);
  const paginatedRows = purchaseRequestRows.slice((page - 1) * pageSize, page * pageSize);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <h2 className="text-2xl font-semibold tracking-tight md:text-3xl">Purchase Request</h2>
        </div>

      </div>

        <Card className="overflow-hidden">
          <div className="bg-gradient-to-r from-primary/5 via-primary/[0.02] to-transparent px-5 pb-4 pt-5 md:px-6">
            <div className="flex items-start justify-between gap-4">
              <div className="min-w-0 flex-1">
                <h2 className="text-xl font-bold tracking-tight text-foreground">RAP locked ready for PR</h2>
                <p className="mt-0.5 text-sm text-muted-foreground">Klik Buat PR untuk mulai menarik item dari RAP locked.</p>
              </div>
            </div>
          </div>
          <CardContent className="space-y-3 px-5 pb-5 md:px-6 md:pb-6">
            {lockedRapWorkspaces.length ? (
              lockedRapWorkspaces.map((workspace) => (
                <div key={workspace.rap.rapId} className="flex flex-col gap-3 rounded-xl px-4 py-3 transition hover:bg-accent/30 sm:flex-row sm:items-center sm:justify-between">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <p className="font-semibold text-foreground">{workspace.projectName}</p>
                      <span className="text-xs text-muted-foreground">—</span>
                      <p className="text-sm text-muted-foreground">{workspace.customerName}</p>
                    </div>
                    <div className="mt-1.5 flex flex-wrap gap-1.5">
                      <Badge label={workspace.rap.rapCode} className="bg-slate-100 text-slate-700" />
                      <Badge label={getRapStatusLabel(workspace.rap.status)} className={getRapStatusClass(workspace.rap.status)} />
                    </div>
                  </div>

                  <div className="flex shrink-0 gap-2">
                    <Link
                      href={`/purchase-requests/new?rapId=${workspace.rap.rapId}`}
                      className={buttonVariants({
                        variant: "outline",
                        className:
                          "h-9 gap-2 border-emerald-300 bg-emerald-50/80 px-3 text-emerald-700 shadow-sm shadow-emerald-950/5 hover:border-emerald-400 hover:bg-emerald-100/90",
                      })}
                    >
                      <ClipboardListIcon className="h-4 w-4 stroke-[2.25]" />
                      <span>Buat PR</span>
                    </Link>
                    <Link href={`/rap/${workspace.rap.rapId}`} className={buttonVariants({ variant: "outline", className: "h-9 px-3" })}>
                      Open RAP detail
                    </Link>
                  </div>
                </div>
              ))
            ) : (
              <div className="rounded-xl border border-dashed border-border/70 px-4 py-6 text-sm text-muted-foreground">
                Belum ada RAP locked yang siap dijadikan PR.
              </div>
            )}
          </CardContent>
        </Card>

      <Card className="overflow-hidden">
        <CardHeader className="p-0 md:p-0 px-8 md:px-8 pt-4 pb-1 md:pt-5 md:pb-1.5">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <CardTitle className="text-lg">PR queue</CardTitle>
            </div>

            <label className="relative flex items-center">
              <SearchIcon className="pointer-events-none absolute left-3 h-4 w-4 text-muted-foreground" />
              <input
                type="search"
                placeholder="Search..."
                className="h-9 w-64 rounded-2xl border border-border/80 bg-background pl-9 pr-4 text-sm outline-none transition placeholder:text-muted-foreground focus:border-primary/40 focus:ring-2 focus:ring-primary/10"
              />
            </label>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="min-w-full border-separate border-spacing-0 text-left text-sm">
              <thead className="sticky top-0 bg-card/95 text-xs uppercase tracking-[0.2em] text-muted-foreground backdrop-blur">
                <tr>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">PR</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Project</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">RAP</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Status</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Total</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Action</th>
                </tr>
              </thead>
              <tbody>
                {paginatedRows.map((row) => {
                  const linkedVendorPo = getVendorPoByPurchaseRequestId(row.id);
                  const actionHref =
                    row.status === "draft" || row.status === "rejected"
                      ? `/purchase-requests/new?rapId=${row.rapId}&requestId=${row.id}`
                      : row.status === "collected"
                        ? linkedVendorPo
                          ? `/vendor-po/${linkedVendorPo.id}`
                          : `/vendor-po/new?prId=${row.id}`
                        : `/purchase-requests/${row.id}`;
                  const actionLabel =
                    row.status === "draft"
                      ? "Continue"
                      : row.status === "rejected"
                        ? "Revise"
                        : row.status === "collected"
                          ? linkedVendorPo
                            ? "Open PO"
                            : "Buat PO"
                          : "Open";

                  return (
                    <tr key={row.id} className="transition hover:bg-accent/60">
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <div className="font-semibold text-foreground">{row.prNumber}</div>
                        <div className="mt-1 text-xs text-muted-foreground">{row.department}</div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <div className="font-semibold text-foreground">{row.projectName}</div>
                        <div className="mt-1 text-xs text-muted-foreground">{row.customerName}</div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <div className="font-semibold text-foreground">{row.rapNumber}</div>
                        <div className="mt-1 text-xs text-muted-foreground">BOQ {row.boqCode}</div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <Badge label={formatPurchaseRequestStatus(row.status)} className={getPurchaseRequestStatusClass(row.status)} />
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{formatPurchaseRequestMoney(row.totalValue)}</td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <Link
                          href={actionHref}
                          className={buttonVariants({
                            variant: "outline",
                            size: "sm",
                            className:
                              row.status === "approved"
                                ? "h-10 gap-2 border-sky-300 bg-sky-50/80 px-3 text-sky-700 shadow-sm shadow-sky-950/5 hover:border-sky-400 hover:bg-sky-100/90"
                                : row.status === "collected"
                                  ? "h-10 gap-2 border-emerald-300 bg-emerald-50/80 px-3 text-emerald-700 shadow-sm shadow-emerald-950/5 hover:border-emerald-400 hover:bg-emerald-100/90"
                                : "h-10 gap-2 border-amber-300 bg-amber-50/80 px-3 text-amber-700 shadow-sm shadow-amber-950/5 hover:border-amber-400 hover:bg-amber-100/90",
                          })}
                        >
                          <FileTextIcon className="h-4 w-4 stroke-[2.25]" />
                          <span>{actionLabel}</span>
                        </Link>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
        </CardContent>
      </Card>

      <div className="flex items-start gap-2 rounded-xl bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
        <DollarSignIcon className="mt-0.5 h-4 w-4 shrink-0" />
        <span>Jika PR berstatus draft atau rejected, tombol action membawa kembali ke layar create PR untuk revisi dan resubmit.</span>
      </div>
    </div>
  );
}
