﻿"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  CalendarIcon,
  FileTextIcon,
  SearchIcon,
  UsersIcon,
} from "@/components/dashboard-icons";
import {
  createPurchaseRequestDraft,
  formatPurchaseRequestMoney,
  getNextPurchaseRequestNumber,
  getPurchaseRequestById,
  getPurchaseRequestByRapId,
  getPurchaseRequestStatusClass,
  getPurchaseRequestStatusLabel,
  submitPurchaseRequest,
  savePurchaseRequestDraft,
  type PurchaseRequestItemRecord,
  type PurchaseRequestRecord,
} from "@/lib/purchase-request-data";
import {
  getRapStatusClass,
  getRapStatusLabel,
  getRapWorkspaceById,
  type CustomerPoRapWorkspace,
  type RapItemCategory,
} from "@/lib/customer-po-rap-data";
import { cn } from "@/lib/utils";

type FormItemState = {
  rapItemId: string;
  itemName: string;
  category: RapItemCategory;
  remainingAmount: number;
  requestedAmount: string;
  notes: string;
  selected: boolean;
};

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

const categorySections: { key: RapItemCategory; label: string; color: string }[] = [
  { key: "material_utama",   label: "Material Utama",   color: "border-blue-400" },
  { key: "material_support", label: "Material Support", color: "border-emerald-400" },
  { key: "servis",           label: "Servis / Jasa",    color: "border-violet-400" },
];

function toNumeric(value: string) {
  const digits = value.replace(/[^\d]/g, "");
  return digits ? Number(digits) : 0;
}

function buildInitialItems(workspace: CustomerPoRapWorkspace, record: PurchaseRequestRecord | null): FormItemState[] {
  return workspace.rap.items.map((item) => {
    const matched = record?.items.find((row) => row.rapItemId === item.id);

    return {
      rapItemId: item.id,
      itemName: item.itemName,
      category: item.category,
      remainingAmount: item.remainingAmount,
      requestedAmount: String(matched?.requestedAmount ?? item.remainingAmount),
      notes: matched?.notes ?? "",
      selected: matched ? true : !record,
    };
  });
}

function toPurchaseRequestItems(items: FormItemState[]) {
  return items
    .filter((item) => item.selected)
    .map<PurchaseRequestItemRecord>((item, index) => ({
      id: `form-${index + 1}`,
      rapItemId: item.rapItemId,
      itemName: item.itemName,
      category: item.category,
      remainingAmount: item.remainingAmount,
      requestedAmount: toNumeric(item.requestedAmount),
      notes: item.notes.trim() || null,
    }));
}

function getFormError(items: FormItemState[]) {
  const selected = items.filter((item) => item.selected);

  if (!selected.length) {
    return "Minimal 1 item harus dipilih.";
  }

  for (const item of selected) {
    const amount = toNumeric(item.requestedAmount);
    if (amount <= 0) {
      return `Nilai diminta untuk ${item.itemName} harus lebih dari 0.`;
    }

    if (amount > item.remainingAmount) {
      return `Nilai diminta untuk ${item.itemName} melebihi plafon tersisa.`;
    }
  }

  return null;
}

export function PurchaseRequestCreateWorkspace({ rapId, requestId }: { rapId: string | undefined; requestId?: string | undefined }) {
  const router = useRouter();
  const explicitRecord = requestId ? getPurchaseRequestById(requestId) : null;
  const workspace = explicitRecord ? getRapWorkspaceById(explicitRecord.rapId) : getRapWorkspaceById(rapId);
  const existingRecord = explicitRecord ?? (workspace ? getPurchaseRequestByRapId(workspace.rap.rapId) : null);
  const [recordId, setRecordId] = useState<string | null>(existingRecord?.id ?? null);
  const [items, setItems] = useState(() => (workspace ? buildInitialItems(workspace, existingRecord) : []));
  const [requester, setRequester] = useState(existingRecord?.requester ?? "GA Admin");
  const [department, setDepartment] = useState(existingRecord?.department ?? "GA Admin");
  const [notes, setNotes] = useState(existingRecord?.notes ?? "Draft PR dibuat dari RAP locked.");
  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 currentRecord = useMemo(() => {
    if (!recordId) {
      return existingRecord;
    }

    return getPurchaseRequestById(recordId) ?? existingRecord;
  }, [existingRecord, recordId]);

  const selectedItems = useMemo(() => items.filter((item) => item.selected), [items]);
  const totalRequested = useMemo(() => selectedItems.reduce((total, item) => total + toNumeric(item.requestedAmount), 0), [selectedItems]);
  const totalRemaining = useMemo(() => selectedItems.reduce((total, item) => total + item.remainingAmount, 0), [selectedItems]);
  const itemCount = selectedItems.length;
  const validationError = useMemo(() => getFormError(items), [items]);
  const isEditable = !currentRecord || currentRecord.status === "draft" || currentRecord.status === "rejected";
  const rapStatusLabel = workspace ? getRapStatusLabel(workspace.rap.status) : "-";
  const rapStatusClass = workspace ? getRapStatusClass(workspace.rap.status) : "bg-slate-100 text-slate-700";
  const prStatusLabel = currentRecord ? getPurchaseRequestStatusLabel(currentRecord.status) : "Draft";
  const prStatusClass = currentRecord ? getPurchaseRequestStatusClass(currentRecord.status) : "bg-slate-100 text-slate-700";

  function handleToggleSelected(itemId: string) {
    if (!isEditable) {
      return;
    }

    setItems((current) =>
      current.map((item) =>
        item.rapItemId === itemId
          ? {
              ...item,
              selected: !item.selected,
              requestedAmount: !item.selected && toNumeric(item.requestedAmount) <= 0 ? String(item.remainingAmount) : item.requestedAmount,
            }
          : item,
      ),
    );
  }

  function updateRequestedAmount(itemId: string, value: string) {
    if (!isEditable) {
      return;
    }

    setItems((current) => current.map((item) => (item.rapItemId === itemId ? { ...item, requestedAmount: value } : item)));
  }

  function updateItemNotes(itemId: string, value: string) {
    if (!isEditable) {
      return;
    }

    setItems((current) => current.map((item) => (item.rapItemId === itemId ? { ...item, notes: value } : item)));
  }

  function buildPayload() {
    return {
      requester,
      department,
      notes: notes.trim() || "Draft PR dibuat dari RAP locked.",
      selectedItems: toPurchaseRequestItems(items),
    };
  }

  function persistDraft() {
    if (!workspace || !isEditable) {
      return;
    }

    const payload = buildPayload();

    if (!recordId) {
      const created = createPurchaseRequestDraft({
        workspace,
        requester: payload.requester,
        department: payload.department,
        prNumber: getNextPurchaseRequestNumber(),
        selectedItems: payload.selectedItems,
        notes: payload.notes,
      });
      setRecordId(created.id);
      setFeedback({ kind: "success", message: "Draft PR tersimpan." });
      return;
    }

    const updated = savePurchaseRequestDraft(recordId, (record) => ({
      ...record,
      requester: payload.requester,
      department: payload.department,
      notes: payload.notes,
      items: payload.selectedItems,
      totalValue: payload.selectedItems.reduce((total, item) => total + item.requestedAmount, 0),
    }));

    if (updated) {
      setFeedback({ kind: "success", message: "Draft PR tersimpan." });
    }
  }

  function submitRequest() {
    if (!workspace || !isEditable) {
      return;
    }

    if (validationError) {
      setFeedback({ kind: "error", message: validationError });
      return;
    }

    const payload = buildPayload();
    let activeRecordId = recordId;

    if (!activeRecordId) {
      const created = createPurchaseRequestDraft({
        workspace,
        requester: payload.requester,
        department: payload.department,
        prNumber: getNextPurchaseRequestNumber(),
        selectedItems: payload.selectedItems,
        notes: payload.notes,
      });
      activeRecordId = created.id;
      setRecordId(created.id);
    } else {
      const updated = savePurchaseRequestDraft(activeRecordId, (record) => ({
        ...record,
        requester: payload.requester,
        department: payload.department,
        notes: payload.notes,
        items: payload.selectedItems,
        totalValue: payload.selectedItems.reduce((total, item) => total + item.requestedAmount, 0),
      }));

      if (updated) {
        activeRecordId = updated.id;
      }
    }

    const submitted = submitPurchaseRequest(activeRecordId);
    if (submitted) {
      router.push(`/purchase-requests/approvals`);
    }
  }

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

          <Link href="/purchase-requests" className={buttonVariants({ className: "w-full sm:w-auto" })}>
            Back to PR queue
          </Link>
        </CardContent>
      </Card>
    );
  }

  if (workspace.rap.status !== "locked") {
    return (
      <Card>
        <CardContent className="space-y-4 p-6">
          <div>
            <h2 className="mt-2 text-2xl font-semibold tracking-tight">RAP belum locked</h2>
          </div>

          <div className="flex flex-col gap-2 sm:flex-row">
            <Link href="/rap" className={buttonVariants({ variant: "outline", className: "w-full sm:w-auto" })}>
              Open RAP workspace
            </Link>
            <Link href={`/rap/${workspace.rap.rapId}`} className={buttonVariants({ className: "w-full sm:w-auto" })}>
              Open RAP detail
            </Link>
          </div>
        </CardContent>
      </Card>
    );
  }

  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">Buat Purchase Request</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/[0.04] to-transparent px-5 py-4 md:px-6 md:py-5">
          <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Info RAP yang menjadi sumber PR</p>
              <div className="mt-2 text-lg font-semibold tracking-tight">{workspace.projectName}</div>
              <p className="mt-1 text-sm text-muted-foreground">{workspace.customerName}</p>
            </div>
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
              <UsersIcon className="h-5 w-5" />
            </div>
          </div>
        </div>
        <div className="divide-y divide-border/50 px-5 py-3 md:px-6">
          <div className="pb-3">
            <div className="grid gap-x-6 gap-y-2 sm:grid-cols-2 xl:grid-cols-4">
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">RAP code</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{workspace.rap.rapCode}</p>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">RAP status</p>
                <div className="mt-1">
                  <Badge label={rapStatusLabel} className={rapStatusClass} />
                </div>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">BOQ</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{workspace.boqCode}</p>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PR status</p>
                <div className="mt-1">
                  <Badge label={prStatusLabel} className={prStatusClass} />
                </div>
              </div>
            </div>
          </div>
          <div className="py-3">
            <div className="grid gap-x-6 gap-y-2 sm:grid-cols-2">
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Requester</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{requester}</p>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Department</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{department}</p>
              </div>
            </div>
          </div>
          {currentRecord ? (
            <div className="pt-3">
              <div className="grid gap-x-6 gap-y-2 md:grid-cols-3">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PR Number</p>
                  <p className="mt-0.5 font-semibold text-foreground">{currentRecord.prNumber}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Created at</p>
                  <p className="mt-0.5 font-semibold text-foreground">{new Date(currentRecord.createdAt).toLocaleString("id-ID")}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Submitted at</p>
                  <p className="mt-0.5 font-semibold text-foreground">{currentRecord.submittedAt ? new Date(currentRecord.submittedAt).toLocaleString("id-ID") : "-"}</p>
                </div>
              </div>
            </div>
          ) : null}
        </div>
      </Card>

      <Card className="overflow-hidden">
        <CardHeader className="border-b border-border/50 px-5 py-3 md:px-6">
          <CardTitle className="text-base font-semibold">Detail PR</CardTitle>
          <p className="mt-0.5 text-sm text-muted-foreground">Requester, department, dan catatan bisa disesuaikan sebelum PR diajukan.</p>
        </CardHeader>
        <CardContent className="space-y-4 p-5 md:p-6">
          <div className="grid gap-4 md:grid-cols-3">
            <div>
              <p className="text-xs font-medium text-muted-foreground">Requester</p>
              <input
                value={requester}
                onChange={(event) => setRequester(event.target.value)}
                disabled={!isEditable}
                className="mt-1.5 h-9 w-full rounded-lg border border-border/80 bg-background px-3 text-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10 disabled:cursor-not-allowed disabled:bg-muted/40"
              />
            </div>
            <div>
              <p className="text-xs font-medium text-muted-foreground">Department</p>
              <select
                value={department}
                onChange={(event) => setDepartment(event.target.value)}
                disabled={!isEditable}
                className="mt-1.5 h-9 w-full rounded-lg border border-border/80 bg-background px-3 text-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10 disabled:cursor-not-allowed disabled:bg-muted/40"
              >
                <option value="GA Admin">GA Admin</option>
                <option value="OPS Admin">OPS Admin</option>
                <option value="Procurement">Procurement</option>
              </select>
            </div>
            <div>
              <p className="text-xs font-medium text-muted-foreground">Catatan</p>
              <input
                value={notes}
                onChange={(event) => setNotes(event.target.value)}
                disabled={!isEditable}
                className="mt-1.5 h-9 w-full rounded-lg border border-border/80 bg-background px-3 text-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10 disabled:cursor-not-allowed disabled:bg-muted/40"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card className="overflow-hidden">
        <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">
            <CardTitle className="text-lg">Pilih Item dari Plafon RAP</CardTitle>
            <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="divide-y divide-border/70">
            {categorySections.map((section) => {
              const sectionItems = 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-1/3 border-b border-border/70 px-3 py-2 pl-12 font-medium">Item RAP</th>
                                <th className="w-1/6 border-b border-border/70 px-3 py-2 font-medium text-right">Plafon Tersisa</th>
                                <th className="w-1/4 border-b border-border/70 px-3 py-2 font-medium text-right">Nilai Diminta</th>
                                <th className="w-1/4 border-b border-border/70 px-3 py-2 font-medium">Catatan</th>
                                <th className="w-12 border-b border-border/70 px-3 py-2 font-medium text-right">Pilih</th>
                              </tr>
                            </thead>
                            <tbody>
                              {sectionItems.map((item) => {
                                const amount = toNumeric(item.requestedAmount);
                                const amountError = item.selected && (amount <= 0 || amount > item.remainingAmount);

                                return (
                                  <tr
                                    key={item.rapItemId}
                                    className={cn(
                                      "cursor-pointer transition hover:bg-accent/30",
                                      item.selected && "bg-primary/5",
                                    )}
                                    onClick={() => handleToggleSelected(item.rapItemId)}
                                  >
                                    <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.rapItemId}</div>
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right">
                                      <div className="font-medium text-foreground">{formatPurchaseRequestMoney(item.remainingAmount)}</div>
                                      <p className="mt-0.5 text-xs text-muted-foreground">Batas maksimal</p>
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right">
                                      <input
                                        value={item.requestedAmount}
                                        onChange={(event) => updateRequestedAmount(item.rapItemId, event.target.value)}
                                        disabled={!item.selected || !isEditable}
                                        inputMode="numeric"
                                        className={cn(
                                          "h-8 w-full rounded-lg border px-2 text-sm text-right outline-none transition focus:ring-2 focus:ring-primary/20",
                                          amountError ? "border-rose-300 bg-rose-50/70 focus:border-rose-400" : "border-border/80 bg-background focus:border-primary/50",
                                          (!item.selected || !isEditable) && "cursor-not-allowed bg-muted/40",
                                        )}
                                      />
                                      {amountError ? <p className="mt-1 text-xs text-rose-600">Nilai harus dalam batas plafon.</p> : null}
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top">
                                      <input
                                        value={item.notes}
                                        onChange={(event) => updateItemNotes(item.rapItemId, event.target.value)}
                                        disabled={!item.selected || !isEditable}
                                        placeholder="Catatan item"
                                        className={cn(
                                          "h-8 w-full rounded-lg border border-border/80 bg-background px-2 text-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10",
                                          (!item.selected || !isEditable) && "cursor-not-allowed bg-muted/40",
                                        )}
                                      />
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right">
                                      <input
                                        type="checkbox"
                                        checked={item.selected}
                                        onChange={() => handleToggleSelected(item.rapItemId)}
                                        onClick={(e) => e.stopPropagation()}
                                        disabled={!isEditable}
                                        className="h-4 w-4 rounded border-border accent-primary"
                                      />
                                    </td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>
                        </div>
                      )}
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="space-y-4 p-4 md:p-5">
          <div className="flex flex-wrap items-baseline gap-x-8 gap-y-2">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Item selected</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{itemCount} item</p>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Total requested</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{formatPurchaseRequestMoney(totalRequested)}</p>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Plafon tersisa</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{formatPurchaseRequestMoney(totalRemaining)}</p>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PR reference</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{currentRecord?.prNumber ?? getNextPurchaseRequestNumber()}</p>
            </div>
          </div>

          <div className="rounded-xl bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
            <div className="flex items-start gap-2">
              <CalendarIcon className="mt-0.5 h-4 w-4 shrink-0" />
              <span>
                {validationError ? validationError : "Minimal 1 item wajib dipilih. Nilai diminta tidak boleh melebihi plafon tersisa dari RAP locked."}
              </span>
            </div>
          </div>

          {feedback ? (
            <div
              className={cn(
                "fixed bottom-6 right-6 z-50 flex w-80 items-start gap-2 rounded-xl px-4 py-3 text-sm shadow-lg backdrop-blur-sm",
                feedback.kind === "success" && "bg-emerald-50 text-emerald-800",
                feedback.kind === "warning" && "bg-amber-50 text-amber-800",
                feedback.kind === "error" && "bg-rose-50 text-rose-800",
              )}
            >
              <span className="flex-1">{feedback.message}</span>
              <button onClick={() => setFeedback(null)} className="shrink-0 text-lg leading-none text-inherit opacity-60 hover:opacity-100">&times;</button>
            </div>
          ) : null}

          {!isEditable ? (
            <div className="rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-700">
              PR ini sudah diproses. Gunakan halaman detail untuk melihat approval trail atau collect status.
            </div>
          ) : null}

          <div className="flex flex-col gap-2 sm:flex-row">
            <Button variant="outline" onClick={persistDraft} disabled={!isEditable} className="h-11 px-4">
              Simpan Draft
            </Button>
            <Button onClick={submitRequest} disabled={!isEditable || !!validationError} className="h-11 gap-2 px-4">
              <FileTextIcon className="h-4 w-4" />
              <span>Ajukan PR</span>
            </Button>

          </div>
        </CardContent>
      </Card>
    </div>
  );
}
