﻿"use client";

import { useState } from "react";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ClipboardListIcon, PackageIcon, SearchIcon } from "@/components/dashboard-icons";
import {
  formatVendorPoMoney,
  getCollectedPurchaseRequests,
  getVendorPoByPurchaseRequestId,
  getVendorPoRows,
  getVendorPoStatusClass,
  getVendorPoStatusLabel,
  getVendorVerificationStatusClass,
  getVendorVerificationStatusLabel,
} from "@/lib/vendor-po-data";
import { getPurchaseRequestStatusClass, getPurchaseRequestStatusLabel } from "@/lib/purchase-request-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 VendorPoWorkspace() {
  const collectedPurchaseRequests = getCollectedPurchaseRequests();
  const vendorPoRows = getVendorPoRows();

  const [page, setPage] = useState(1);
  const pageSize = 5;
  const totalPages = Math.ceil(vendorPoRows.length / pageSize);
  const paginatedRows = vendorPoRows.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">Vendor PO Internal</h2>
        </div>

        <div className="flex w-full flex-col gap-2 sm:flex-row lg:w-auto">
        </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">Collected PR ready for PO</h2>
              <p className="mt-0.5 text-sm text-muted-foreground">Gunakan tombol di setiap baris untuk membuat atau membuka PO internal.</p>
            </div>
          </div>
        </div>
        <CardContent className="space-y-3 px-5 pb-5 md:px-6 md:pb-6">
          {collectedPurchaseRequests.length ? (
            collectedPurchaseRequests.map((row) => {
              const existingPo = getVendorPoByPurchaseRequestId(row.id);
              const actionHref = existingPo ? `/vendor-po/${existingPo.id}` : `/vendor-po/new?prId=${row.id}`;
              const actionLabel = existingPo ? "Open PO" : "Buat PO";

              return (
                <div key={row.id} 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">{row.prNumber}</p>
                      <span className="text-xs text-muted-foreground">—</span>
                      <p className="text-sm text-muted-foreground">{row.projectName}</p>
                    </div>
                    <div className="mt-1.5 flex flex-wrap gap-1.5">
                      <Badge label={getPurchaseRequestStatusLabel(row.status)} className={getPurchaseRequestStatusClass(row.status)} />
                      <Badge label={row.rapNumber} className="bg-slate-100 text-slate-700" />
                      <Badge label={existingPo ? `PO: ${existingPo.poNumber}` : "Belum ada PO"} className="bg-blue-100 text-blue-700" />
                    </div>
                  </div>

                  <div className="flex shrink-0 gap-2">
                    <Link
                      href={actionHref}
                      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>{actionLabel}</span>
                    </Link>
                    <Link href={`/purchase-requests/${row.id}`} className={buttonVariants({ variant: "outline", className: "h-9 px-3" })}>
                      Open PR 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 PR yang sudah collected.
            </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">PO 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">PO</th>
                  <th className="border-b border-border/70 px-5 py-2 font-semibold">Vendor</th>
                  <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">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>
                {vendorPoRows.length ? (
                  paginatedRows.map((row) => (
                    <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.poNumber}</div>
                        <div className="mt-1 text-xs text-muted-foreground">{row.projectName}</div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <div className="font-semibold text-foreground">{row.vendorName}</div>
                        <div className="mt-2 flex flex-wrap gap-2">
                          <Badge
                            label={getVendorVerificationStatusLabel(row.vendorVerificationStatus)}
                            className={getVendorVerificationStatusClass(row.vendorVerificationStatus)}
                          />
                        </div>
                      </td>
                      <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.rapNumber}</div>
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <Badge label={getVendorPoStatusLabel(row.status)} className={getVendorPoStatusClass(row.status)} />
                      </td>
                      <td className="border-b border-border/70 px-5 py-4 align-top font-medium">{formatVendorPoMoney(row.totalPoAmount)}</td>
                      <td className="border-b border-border/70 px-5 py-4 align-top">
                        <Link
                          href={`/vendor-po/${row.id}`}
                          className={buttonVariants({
                            variant: "outline",
                            size: "sm",
                            className:
                              row.status === "issued"
                                ? "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 === "approved"
                                  ? "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",
                          })}
                        >
                          <PackageIcon className="h-4 w-4 stroke-[2.25]" />
                          <span>Open</span>
                        </Link>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td className="px-5 py-8 text-center text-sm text-muted-foreground" colSpan={6}>
                      Belum ada PO internal yang dibuat.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

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