﻿"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ActionGuard } from "@/components/action-guard";
import {
  CalendarIcon,
  PackageIcon,
  PencilIcon,
  FileTextIcon,
  ShieldCheckIcon,
} from "@/components/dashboard-icons";
import {
  approveVendorPo,
  buildVendorPoApprovalTrail,
  buildVendorPoSummary,
  collectVendorPo,
  formatVendorPoMoney,
  getVendorPoApprovalRoleLabel,
  getVendorPoApprovalStatusLabel,
  getVendorPoById,
  getVendorPoStatusClass,
  getVendorPoStatusLabel,
  getVendorVerificationStatusClass,
  getVendorVerificationStatusLabel,
  rejectVendorPo,
  submitVendorPoForApproval,
  type VendorPoApprovalRole,
  type VendorPoRecord,
  vendorCatalog,
} from "@/lib/vendor-po-data";
import { getPurchaseRequestById, getPurchaseRequestStatusClass, getPurchaseRequestStatusLabel } from "@/lib/purchase-request-data";
import { getRapStatusClass, getRapStatusLabel, getRapWorkspaceById, type RapItemCategory } from "@/lib/customer-po-rap-data";
import { useAuth } from "@/lib/auth-context";
import { cn } from "@/lib/utils";

type FeedbackState = {
  kind: "success" | "warning" | "error";
  message: string;
};

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>;
}

function formatDateTime(value: string | null) {
  if (!value) {
    return "-";
  }

  return new Date(value).toLocaleString("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function buildFallbackRole(record: VendorPoRecord) {
  return record.approvals.find((approval) => approval.status === "pending")?.role ?? record.approvals[0]?.role ?? "procurement_manager";
}

export function VendorPoDetailWorkspace({ vendorPoId }: { vendorPoId: string | undefined }) {
  const [record, setRecord] = useState(() => getVendorPoById(vendorPoId));
  const [selectedRole, setSelectedRole] = useState<VendorPoApprovalRole>(() => (record ? buildFallbackRole(record) : "procurement_manager"));
  const [actionNotes, setActionNotes] = useState("");
  const [feedback, setFeedback] = useState<FeedbackState | null>(null);
  const [expandedSections, setExpandedSections] = useState<Record<RapItemCategory, boolean>>({
    material_utama: true,
    material_support: true,
    servis: true,
  });

  function toggleSection(key: RapItemCategory) {
    setExpandedSections((prev) => ({ ...prev, [key]: !prev[key] }));
  }
  const { activeRole } = useAuth();

  const linkedPurchaseRequest = useMemo(() => (record ? getPurchaseRequestById(record.prId) : null), [record]);
  const linkedRap = useMemo(() => (record ? getRapWorkspaceById(record.rapId) : null), [record]);
  const selectedVendor = useMemo(() => {
    if (!record) {
      return null;
    }

    return vendorCatalog.find((vendor) => vendor.id === record.vendorId) ?? null;
  }, [record]);
  const summary = useMemo(() => (record ? buildVendorPoSummary(record) : null), [record]);
  const approvalTrail = useMemo(() => (record ? buildVendorPoApprovalTrail(record) : []), [record]);
  const effectiveSelectedRole =
    record && activeRole && record.approvals.some((approval) => approval.role === activeRole)
      ? (activeRole as VendorPoApprovalRole)
      : selectedRole;
  const canManageApproval = activeRole === effectiveSelectedRole || activeRole === "admin";
  const canSubmitRecord = activeRole === "procurement" || activeRole === "admin";
  const canCollectRecord = activeRole === "procurement" || activeRole === "admin";

  if (!record) {
    return (
      <Card>
        <CardContent className="space-y-4 p-6">
          <div>
            <h2 className="mt-2 text-2xl font-semibold tracking-tight">PO tidak ditemukan</h2>
          </div>

        </CardContent>
      </Card>
    );
  }

  const canSubmit = record.status === "draft" || record.status === "rejected";
  const canApprove = record.status === "pending_approval";
  const canCollect = record.status === "approved";
  function handleSubmit() {
    if (!canSubmit) {
      return;
    }
    if (!canSubmitRecord) {
      return;
    }

    const currentRecord = record;
    if (!currentRecord) {
      return;
    }

    const updated = submitVendorPoForApproval(currentRecord.id);
    if (updated) {
      setRecord(updated);
      setSelectedRole(buildFallbackRole(updated));
      setFeedback({
        kind: "success",
        message: "PO internal sudah diajukan ke approval Procurement Manager dan Direktur.",
      });
    }
  }

  function handleApprove() {
    if (!canApprove) {
      return;
    }
    if (!canManageApproval) {
      return;
    }

    const currentRecord = record;
    if (!currentRecord) {
      return;
    }

    const updated = approveVendorPo(currentRecord.id, effectiveSelectedRole, actionNotes.trim() || "Disetujui setelah review vendor PO internal.");
    if (updated) {
      setRecord(updated);
      setSelectedRole(buildFallbackRole(updated));
      setFeedback({
        kind: updated.status === "approved" ? "success" : "warning",
        message:
          updated.status === "approved"
            ? "PO internal sudah approved penuh dan siap di-collect."
            : `${getVendorPoApprovalRoleLabel(effectiveSelectedRole)} menyetujui PO ini.`,
      });
      setActionNotes("");
    }
  }

  function handleReject() {
    if (!canApprove) {
      return;
    }
    if (!canManageApproval) {
      return;
    }

    if (!actionNotes.trim()) {
      setFeedback({ kind: "error", message: "Catatan penolakan wajib diisi." });
      return;
    }

    const currentRecord = record;
    if (!currentRecord) {
      return;
    }

    const updated = rejectVendorPo(currentRecord.id, effectiveSelectedRole, actionNotes.trim());
    if (updated) {
      setRecord(updated);
      setSelectedRole(buildFallbackRole(updated));
      setFeedback({
        kind: "warning",
        message: `${getVendorPoApprovalRoleLabel(effectiveSelectedRole)} menolak PO ini. Status kembali menjadi Rejected.`,
      });
      setActionNotes("");
    }
  }

  function handleCollect() {
    if (!canCollect) {
      return;
    }
    if (!canCollectRecord) {
      return;
    }

    const currentRecord = record;
    if (!currentRecord) {
      return;
    }

    const updated = collectVendorPo(currentRecord.id, "Procurement");
    if (updated) {
      setRecord(updated);
      setFeedback({
        kind: "success",
        message: "PO sudah di-collect Procurement dan status proyek masuk ke execution.",
      });
    }
  }

  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">{record.poNumber}</h2>
        </div>

      </div>

      {feedback ? (
        <div
          className={cn(
            "fixed bottom-6 right-6 z-50 flex w-80 items-start gap-3 rounded-xl border px-4 py-3 text-sm shadow-[0_20px_60px_rgba(0,0,0,0.15)] backdrop-blur-sm",
            feedback.kind === "success" && "border-emerald-200 bg-emerald-50/95 text-emerald-800",
            feedback.kind === "warning" && "border-amber-200 bg-amber-50/95 text-amber-800",
            feedback.kind === "error" && "border-rose-200 bg-rose-50/95 text-rose-800",
          )}
        >
          <div className="flex-1">
            <div className="flex items-start gap-3">
              <ShieldCheckIcon className="mt-0.5 h-4 w-4 shrink-0" />
              <span>{feedback.message}</span>
            </div>
            {record.status === "issued" && linkedPurchaseRequest ? (
              <div className="mt-3 flex flex-wrap gap-2">
                <Link href={`/purchase-requests/${linkedPurchaseRequest.id}`} className={buttonVariants({ variant: "outline", size: "sm", className: "h-8 px-3 text-xs" })}>
                  Buka PR terkait
                </Link>
              </div>
            ) : null}
          </div>
          <button type="button" onClick={() => setFeedback(null)} className="shrink-0 text-muted-foreground hover:text-foreground">&times;</button>
        </div>
      ) : null}

      {record.status === "rejected" ? (
        <div className="rounded-xl bg-rose-50 px-4 py-3 text-sm text-rose-800">
          PO ini sudah ditolak. Revisi bisa dilakukan dari create screen lalu ajukan ulang.
        </div>
      ) : null}

      {record.status === "draft" ? (
        <div className="rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-700">
          PO masih draft. Gunakan tombol submit untuk mengirim ke approval Procurement Manager dan Direktur.
        </div>
      ) : null}

      {record.status === "approved" ? (
        <div className="rounded-xl bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
          PO sudah approved penuh. Lanjutkan dengan Collect PO agar status menjadi issued.
        </div>
      ) : null}

      {record.status === "issued" ? (
        <div className="rounded-xl bg-sky-50 px-4 py-3 text-sm text-sky-800">
          PO ini sudah issued pada {formatDateTime(record.issuedAt)} oleh {record.issuedBy ?? "-"}.
        </div>
      ) : null}

        <Card className="overflow-hidden">
          <div className="bg-gradient-to-r from-primary/5 via-primary/[0.02] to-transparent px-5 pb-5 pt-5 md:px-6">
            <div className="flex items-start justify-between gap-4">
              <div className="min-w-0 flex-1">
                <p className="text-xs font-medium uppercase tracking-[0.15em] text-primary/60">Info PO & PR</p>
                <h2 className="mt-1.5 text-xl font-bold tracking-tight text-foreground">{record.projectName}</h2>
                <p className="mt-0.5 text-sm text-muted-foreground">{record.customerName}</p>
              </div>
              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary shadow-sm">
                <PackageIcon className="h-5 w-5" />
              </div>
            </div>
          </div>

          <div className="divide-y divide-border/40 px-5 py-4 md:px-6">
            <div className="grid gap-x-8 gap-y-4 pb-4 sm:grid-cols-2 xl:grid-cols-4">
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PO Number</p>
                <p className="mt-1 font-semibold">{record.poNumber}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Status</p>
                <div className="mt-1">
                  <Badge label={getVendorPoStatusLabel(record.status)} className={getVendorPoStatusClass(record.status)} />
                </div>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PR</p>
                <p className="mt-1 font-semibold">{record.prNumber}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">RAP</p>
                <p className="mt-1 font-semibold">{record.rapNumber}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Vendor</p>
                <p className="mt-1 font-semibold">{record.vendorName}</p>
                <div className="mt-1">
                  <Badge
                    label={getVendorVerificationStatusLabel(record.vendorVerificationStatus)}
                    className={getVendorVerificationStatusClass(record.vendorVerificationStatus)}
                  />
                </div>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PR status</p>
                <div className="mt-1">
                  <Badge label={getPurchaseRequestStatusLabel(linkedPurchaseRequest?.status ?? "collected")} className={getPurchaseRequestStatusClass(linkedPurchaseRequest?.status ?? "collected")} />
                </div>
                <p className="mt-0.5 text-xs text-muted-foreground">Collected by {linkedPurchaseRequest?.collectedBy ?? "-"}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Created</p>
                <p className="mt-1 font-semibold">{formatDateTime(record.createdAt)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Submitted</p>
                <p className="mt-1 font-semibold">{formatDateTime(record.submittedAt)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Approved</p>
                <p className="mt-1 font-semibold">{formatDateTime(record.approvedAt)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Issued</p>
                <p className="mt-1 font-semibold">{formatDateTime(record.issuedAt)}</p>
              </div>
            </div>

            <div className="grid gap-x-8 gap-y-4 pt-4 sm:grid-cols-2">
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Total requested</p>
                <p className="mt-1 text-lg font-bold tracking-tight">{formatVendorPoMoney(summary?.requested ?? record.totalRequested)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Total PO</p>
                <p className="mt-1 text-lg font-bold tracking-tight">{formatVendorPoMoney(summary?.poAmount ?? record.totalPoAmount)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Efficiency</p>
                <p className="mt-1 text-lg font-bold tracking-tight">{formatVendorPoMoney(summary?.savings ?? 0)}</p>
              </div>
              <div>
                <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Approval trail</p>
                <p className="mt-1 text-sm font-semibold">
                  {summary?.approved ?? 0}/2 approved, {summary?.pending ?? 0} pending
                </p>
              </div>
            </div>

            {selectedVendor ? (
              <div className="flex flex-wrap gap-x-8 gap-y-2 pt-4 text-sm">
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">PIC</span>
                  <p className="mt-0.5 font-semibold text-foreground">{selectedVendor.pic}</p>
                </div>
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Phone</span>
                  <p className="mt-0.5 font-semibold text-foreground">{selectedVendor.phone}</p>
                </div>
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Email</span>
                  <p className="mt-0.5 font-semibold text-foreground">{selectedVendor.email}</p>
                </div>
              </div>
            ) : null}

            {linkedRap ? (
              <div className="flex flex-wrap gap-x-8 gap-y-2 pt-4 text-sm">
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">RAP code</span>
                  <p className="mt-0.5 font-semibold text-foreground">{linkedRap.rap.rapCode}</p>
                </div>
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">RAP status</span>
                  <div className="mt-0.5">
                    <Badge label={getRapStatusLabel(linkedRap.rap.status)} className={getRapStatusClass(linkedRap.rap.status)} />
                  </div>
                </div>
                <div>
                  <span className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Project</span>
                  <p className="mt-0.5 font-semibold text-foreground">{linkedRap.projectName}</p>
                </div>
              </div>
            ) : null}
          </div>
        </Card>

      <Card>
        <CardHeader className="p-0 md:p-0 px-5 md:px-6 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">Item PO Internal</CardTitle>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="divide-y divide-border/70">
            {[
              { key: "material_utama" as RapItemCategory, label: "Material Utama", color: "border-l-blue-500" },
              { key: "material_support" as RapItemCategory, label: "Material Support", color: "border-l-emerald-500" },
              { key: "servis" as RapItemCategory, label: "Servis", color: "border-l-violet-500" },
            ].map((section) => {
              const sectionItems = record.items.filter((item) => item.category === section.key);

              return (
                <div key={section.key} className={cn("border-l-4", section.color)}>
                  <div className="flex items-center justify-between px-5 py-4">
                    <button type="button" onClick={() => toggleSection(section.key)} className="flex items-center gap-3 text-left transition hover:opacity-70">
                      <svg
                        className={cn("h-4 w-4 text-muted-foreground transition-transform duration-200", expandedSections[section.key] && "rotate-90")}
                        fill="none"
                        viewBox="0 0 24 24"
                        strokeWidth={2.5}
                        stroke="currentColor"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                      </svg>
                      <span className="font-semibold text-foreground">{section.label}</span>
                      <span className="rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
                        {sectionItems.length} item{sectionItems.length !== 1 ? "s" : ""}
                      </span>
                    </button>
                  </div>

                  {expandedSections[section.key] ? (
                    <div className="border-t border-border/50">
                      {sectionItems.length === 0 ? (
                        <div className="px-5 py-6 text-center text-sm text-muted-foreground">Belum ada item di kategori ini.</div>
                      ) : (
                        <div className="overflow-x-auto pr-4 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border [&::-webkit-scrollbar-track]:bg-transparent">
                          <table className="min-w-full border-separate border-spacing-0 text-left text-sm">
                            <thead>
                              <tr className="text-sm text-muted-foreground">
                                <th className="w-[28%] border-b border-border/70 px-3 py-2 pl-12 font-medium">Item</th>
                                <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Requested</th>
                                <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">PO amount</th>
                                <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Variance</th>
                                <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium">Notes</th>
                              </tr>
                            </thead>
                            <tbody>
                              {sectionItems.map((item) => {
                                const variance = item.requestedAmount - item.poAmount;

                                return (
                                  <tr key={item.id} className="transition hover:bg-accent/30">
                                    <td className="border-b border-border/30 px-3 py-3 pl-12 align-top">
                                      <div className="font-semibold text-foreground">{item.itemName}</div>
                                      <div className="mt-0.5 text-xs text-muted-foreground">{item.purchaseRequestItemId}</div>
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right font-medium">{formatVendorPoMoney(item.requestedAmount)}</td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right font-medium">{formatVendorPoMoney(item.poAmount)}</td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right font-medium">{formatVendorPoMoney(variance)}</td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-muted-foreground">{item.notes ?? "-"}</td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>
                        </div>
                      )}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-3">
          <CardTitle>Status Approval</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex flex-wrap gap-2">
            {approvalTrail.map((approval) => (
              <button
                key={approval.role}
                type="button"
                onClick={() => setSelectedRole(approval.role)}
                className={cn(
                  "rounded-full border px-4 py-2 text-sm font-semibold transition",
                  effectiveSelectedRole === approval.role
                    ? "border-primary bg-primary text-primary-foreground"
                    : "border-border bg-background text-foreground hover:bg-accent",
                )}
              >
                {getVendorPoApprovalRoleLabel(approval.role)}
              </button>
            ))}
          </div>

          <div className="space-y-1">
            {approvalTrail.map((approval) => (
              <div
                key={approval.role}
                className={cn(
                  "flex items-center justify-between gap-3 rounded-xl px-4 py-3 transition",
                  approval.role === effectiveSelectedRole && approval.status === "pending"
                    ? "bg-primary/5"
                    : "hover:bg-accent/30",
                )}
              >
                <div className="flex items-center gap-3">
                  <span
                    className={cn(
                      "h-2 w-2 shrink-0 rounded-full",
                      approval.status === "approved" && "bg-emerald-500",
                      approval.status === "rejected" && "bg-rose-500",
                      approval.status === "pending" && "bg-amber-400",
                    )}
                  />
                  <div>
                    <p className="text-sm font-medium">{getVendorPoApprovalRoleLabel(approval.role)}</p>
                    <p className="text-xs text-muted-foreground">{formatDateTime(approval.decidedAt)}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  {approval.notes && approval.status !== "pending" ? (
                    <span className="hidden text-xs text-muted-foreground sm:inline">{approval.notes}</span>
                  ) : null}
                  <span
                    className={cn(
                      "rounded-full px-2.5 py-0.5 text-xs font-medium",
                      approval.status === "approved" && "bg-emerald-100 text-emerald-700",
                      approval.status === "rejected" && "bg-rose-100 text-rose-700",
                      approval.status === "pending" && "bg-amber-100 text-amber-700",
                    )}
                  >
                    {getVendorPoApprovalStatusLabel(approval.status)}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <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>
              <p className="text-xs font-medium uppercase tracking-[0.15em] text-primary/60">Approval action</p>
              <h2 className="mt-1.5 text-xl font-bold tracking-tight text-foreground">Review & putuskan PO</h2>
            </div>
            <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary shadow-sm">
              <ShieldCheckIcon className="h-5 w-5" />
            </div>
          </div>
        </div>
        <CardContent className="space-y-4 px-5 pb-5 md:px-6 md:pb-6">
          <div className="flex flex-wrap gap-x-8 gap-y-3 text-sm">
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Selected role</p>
              <p className="mt-0.5 font-semibold">{getVendorPoApprovalRoleLabel(effectiveSelectedRole)}</p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Current status</p>
              <div className="mt-0.5">
                <Badge label={getVendorPoStatusLabel(record.status)} className={getVendorPoStatusClass(record.status)} />
              </div>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Issued by</p>
              <p className="mt-0.5 font-semibold">{record.issuedBy ?? "-"}</p>
            </div>
          </div>

          {canSubmit ? (
            <div className="flex items-start gap-2 rounded-xl bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
              <CalendarIcon className="mt-0.5 h-4 w-4 shrink-0" />
              <span>PO masih draft atau rejected. Submit agar masuk ke approval Procurement Manager dan Direktur.</span>
            </div>
          ) : null}

          {canApprove ? (
            <div className="space-y-2">
              <label className="text-xs font-medium uppercase tracking-[0.1em] text-muted-foreground">Approval notes</label>
              <textarea
                rows={3}
                value={actionNotes}
                onChange={(event) => setActionNotes(event.target.value)}
                placeholder="Catatan persetujuan atau alasan reject..."
                className="w-full rounded-xl border border-border/80 bg-background px-4 py-3 text-sm outline-none transition placeholder:text-muted-foreground focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
              />
              <p className="text-xs text-muted-foreground">Reject wajib memakai catatan. Approve boleh memakai catatan opsional.</p>
            </div>
          ) : null}

          {canCollect ? (
            <div className="rounded-xl bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
              PO sudah approved dan dapat di-collect.
            </div>
          ) : null}

          <div className="flex flex-wrap gap-2">
            <ActionGuard
              allowedRoles={["procurement", "admin"]}
              fallback={<div className="rounded-full border border-dashed border-border px-4 py-2 text-sm text-muted-foreground">Submit hanya untuk Procurement.</div>}
            >
              {canSubmit ? (
                <Button variant="outline" onClick={handleSubmit} className="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">
                  <FileTextIcon className="h-4 w-4" />
                  <span>Submit for approval</span>
                </Button>
              ) : null}
            </ActionGuard>
            <ActionGuard
              allowedRoles={[effectiveSelectedRole, "admin"]}
              fallback={<div className="rounded-full border border-dashed border-border px-4 py-2 text-sm text-muted-foreground">Role aktif tidak bisa memutuskan PO ini.</div>}
            >
              {canApprove ? (
                <>
                  <Button variant="outline" onClick={handleReject} className="h-10 px-4 text-rose-700">
                    Reject
                  </Button>
                  <Button onClick={handleApprove} className="h-10 px-4">
                    Approve
                  </Button>
                </>
              ) : null}
            </ActionGuard>
            <ActionGuard
              allowedRoles={["procurement", "admin"]}
              fallback={<div className="rounded-full border border-dashed border-border px-4 py-2 text-sm text-muted-foreground">Collect PO hanya untuk Procurement.</div>}
            >
              {canCollect ? (
                <Button
                  variant="outline"
                  onClick={handleCollect}
                  className="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"
                >
                  <ShieldCheckIcon className="h-4 w-4" />
                  <span>Collect PO</span>
                </Button>
              ) : null}
            </ActionGuard>
            {(record.status === "draft" || record.status === "rejected") && linkedPurchaseRequest ? (
              <ActionGuard
                allowedRoles={["procurement", "admin"]}
                fallback={<div className="rounded-full border border-dashed border-border px-4 py-2 text-sm text-muted-foreground">Revise PO hanya untuk Procurement.</div>}
              >
                <Link
                  href={`/vendor-po/new?prId=${record.prId}`}
                  className={buttonVariants({ variant: "outline", className: "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" })}
                >
                  <PencilIcon className="h-4 w-4" />
                  <span>Revise PO</span>
                </Link>
              </ActionGuard>
            ) : null}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
