﻿"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,
  PackageIcon,
  SearchIcon,
  ShieldCheckIcon,
  UsersIcon,
} from "@/components/dashboard-icons";
import {
  createVendorPoDraft,
  formatVendorPoMoney,
  getNextVendorPoNumber,
  getVendorPoByPurchaseRequestId,
  getVendorPoStatusClass,
  getVendorPoStatusLabel,
  getVendorVerificationStatusClass,
  getVendorVerificationStatusLabel,
  getWorkspaceForVendorPo,
  saveVendorPoDraft,
  submitVendorPoForApproval,
  type VendorPoItemRecord,
  type VendorPoRecord,
  vendorCatalog,
} from "@/lib/vendor-po-data";
import { getPurchaseRequestById, getPurchaseRequestStatusClass, getPurchaseRequestStatusLabel } from "@/lib/purchase-request-data";
import { getRapStatusClass, getRapStatusLabel, type RapItemCategory } from "@/lib/customer-po-rap-data";
import { cn } from "@/lib/utils";

type FormItemState = {
  purchaseRequestItemId: string;
  itemName: string;
  category: RapItemCategory;
  requestedAmount: number;
  poAmount: 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>;
}

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

function buildInitialItems(purchaseRequestId: string, record: VendorPoRecord | null): FormItemState[] {
  const purchaseRequest = getPurchaseRequestById(purchaseRequestId);
  if (!purchaseRequest) {
    return [];
  }

  return purchaseRequest.items.map((item) => {
    const matched = record?.items.find((row) => row.purchaseRequestItemId === item.id);

    return {
      purchaseRequestItemId: item.id,
      itemName: item.itemName,
      category: item.category,
      requestedAmount: item.requestedAmount,
      poAmount: String(matched?.poAmount ?? item.requestedAmount),
      notes: matched?.notes ?? "",
      selected: matched ? true : true,
    };
  });
}

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

function getFormError(items: FormItemState[], vendorId: string) {
  if (!vendorId) {
    return "Vendor wajib dipilih.";
  }

  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.poAmount);

    if (amount <= 0) {
      return `Nilai PO untuk ${item.itemName} harus lebih dari 0.`;
    }

    if (amount > item.requestedAmount) {
      return `Nilai PO untuk ${item.itemName} tidak boleh melebihi requested amount.`;
    }
  }

  return null;
}

function getVendorById(vendorId: string) {
  return vendorCatalog.find((vendor) => vendor.id === vendorId) ?? null;
}

export function VendorPoCreateWorkspace({ prId }: { prId: string | undefined }) {
  const router = useRouter();
  const purchaseRequest = useMemo(() => (prId ? getPurchaseRequestById(prId) : null), [prId]);
  const existingRecord = useMemo(() => (prId ? getVendorPoByPurchaseRequestId(prId) : null), [prId]);
  const editableRecord = existingRecord && (existingRecord.status === "draft" || existingRecord.status === "rejected") ? existingRecord : null;
  const workspace = useMemo(() => (purchaseRequest ? getWorkspaceForVendorPo(purchaseRequest.id) : null), [purchaseRequest]);
  const [recordId, setRecordId] = useState<string | null>(editableRecord?.id ?? null);
  const [selectedVendorId, setSelectedVendorId] = useState<string>(
    editableRecord?.vendorId ?? vendorCatalog.find((vendor) => vendor.verificationStatus === "verified")?.id ?? vendorCatalog[0]?.id ?? "",
  );
  const [items, setItems] = useState(() => buildInitialItems(prId ?? "", editableRecord));
  const [searchQuery, setSearchQuery] = useState("");
  const [notes, setNotes] = useState(editableRecord?.notes ?? "Draft PO dibuat dari PR collected untuk approval Procurement.");
  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 selectedVendor = useMemo(() => getVendorById(selectedVendorId), [selectedVendorId]);
  const currentRecord = useMemo(() => {
    if (!recordId) {
      return editableRecord;
    }

    return getVendorPoByPurchaseRequestId(prId) ?? editableRecord;
  }, [editableRecord, prId, recordId]);
  const selectedItems = useMemo(() => items.filter((item) => item.selected), [items]);
  const totalRequested = useMemo(() => selectedItems.reduce((total, item) => total + item.requestedAmount, 0), [selectedItems]);
  const totalPoAmount = useMemo(() => selectedItems.reduce((total, item) => total + toNumeric(item.poAmount), 0), [selectedItems]);
  const validationError = useMemo(() => getFormError(items, selectedVendorId), [items, selectedVendorId]);
  const isEditable = !currentRecord || currentRecord.status === "draft" || currentRecord.status === "rejected";

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

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

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

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

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

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

  function buildPayload() {
    const vendor = getVendorById(selectedVendorId);

    return {
      vendor,
      notes: notes.trim() || "Draft PO dibuat dari PR collected untuk approval Procurement.",
      selectedItems: toVendorPoItems(items),
    };
  }

  function persistDraft() {
    if (!purchaseRequest || purchaseRequest.status !== "collected" || !isEditable || !selectedVendor) {
      return;
    }

    const payload = buildPayload();

    if (!recordId) {
      const created = createVendorPoDraft({
        purchaseRequest,
        vendor: selectedVendor,
        poNumber: getNextVendorPoNumber(),
        selectedItems: payload.selectedItems,
        notes: payload.notes,
      });
      setRecordId(created.id);
      setFeedback({ kind: "success", message: "Draft PO internal tersimpan." });
      return;
    }

    const updated = saveVendorPoDraft(recordId, (record) => ({
      ...record,
      vendorId: selectedVendor.id,
      vendorName: selectedVendor.name,
      vendorVerificationStatus: selectedVendor.verificationStatus,
      notes: payload.notes,
      items: payload.selectedItems,
      totalRequested: payload.selectedItems.reduce((total, item) => total + item.requestedAmount, 0),
      totalPoAmount: payload.selectedItems.reduce((total, item) => total + item.poAmount, 0),
    }));

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

  function submitRequest() {
    if (!purchaseRequest || purchaseRequest.status !== "collected" || !selectedVendor) {
      return;
    }

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

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

    if (!activeRecordId) {
      const created = createVendorPoDraft({
        purchaseRequest,
        vendor: selectedVendor,
        poNumber: getNextVendorPoNumber(),
        selectedItems: payload.selectedItems,
        notes: payload.notes,
      });
      activeRecordId = created.id;
      setRecordId(created.id);
    } else {
      const updated = saveVendorPoDraft(activeRecordId, (record) => ({
        ...record,
        vendorId: selectedVendor.id,
        vendorName: selectedVendor.name,
        vendorVerificationStatus: selectedVendor.verificationStatus,
        notes: payload.notes,
        items: payload.selectedItems,
        totalRequested: payload.selectedItems.reduce((total, item) => total + item.requestedAmount, 0),
        totalPoAmount: payload.selectedItems.reduce((total, item) => total + item.poAmount, 0),
      }));

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

    const submitted = activeRecordId ? submitVendorPoForApproval(activeRecordId) : null;
    if (submitted) {
      router.push(`/vendor-po/${submitted.id}`);
    }
  }

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

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

  if (purchaseRequest.status !== "collected") {
    return (
      <Card>
        <CardContent className="space-y-4 p-6">
          <div>
            <h2 className="mt-2 text-2xl font-semibold tracking-tight">PR belum collected</h2>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (existingRecord && !editableRecord) {
    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">PO sudah ada untuk PR ini</h2>
        </div>

          <div className="flex flex-col gap-2 sm:flex-row">
            <Link href={`/vendor-po/${existingRecord.id}`} className={buttonVariants({ className: "w-full sm:w-auto" })}>
              Open PO detail
            </Link>
          </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">PO aktif untuk PR ini</p>
                <div className="mt-2 text-lg font-semibold tracking-tight">{existingRecord.poNumber}</div>
                <p className="mt-1 text-sm text-muted-foreground">{existingRecord.projectName}</p>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <PackageIcon 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">Vendor</p>
                  <p className="mt-0.5 text-sm font-semibold text-foreground">{existingRecord.vendorName}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Status</p>
                  <div className="mt-1">
                    <Badge label={getVendorPoStatusLabel(existingRecord.status)} className={getVendorPoStatusClass(existingRecord.status)} />
                  </div>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PO value</p>
                  <p className="mt-0.5 text-sm font-semibold text-foreground">{formatVendorPoMoney(existingRecord.totalPoAmount)}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Verified</p>
                  <div className="mt-1">
                    <Badge
                      label={getVendorVerificationStatusLabel(existingRecord.vendorVerificationStatus)}
                      className={getVendorVerificationStatusClass(existingRecord.vendorVerificationStatus)}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-semibold tracking-tight md:text-3xl">Buat Vendor PO Internal</h2>
      </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 PR & RAP yang menjadi sumber PO</p>
              <div className="mt-2 text-lg font-semibold tracking-tight">{purchaseRequest.projectName}</div>
              <p className="mt-1 text-sm text-muted-foreground">{purchaseRequest.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">PR Number</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{purchaseRequest.prNumber}</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={getPurchaseRequestStatusLabel(purchaseRequest.status)} className={getPurchaseRequestStatusClass(purchaseRequest.status)} />
                </div>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">RAP</p>
                <p className="mt-0.5 text-sm font-semibold text-foreground">{purchaseRequest.rapNumber}</p>
              </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">{purchaseRequest.boqCode}</p>
              </div>
            </div>
          </div>
          {workspace ? (
            <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">RAP code</p>
                  <p className="mt-0.5 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={getRapStatusLabel(workspace.rap.status)} className={getRapStatusClass(workspace.rap.status)} />
                  </div>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PR collected by</p>
                  <p className="mt-0.5 font-semibold text-foreground">{purchaseRequest.collectedBy ?? "-"}</p>
                </div>
              </div>
            </div>
          ) : null}
        </div>
      </Card>

      <Card>
        <CardHeader>
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <CardTitle>Pilih vendor</CardTitle>
              <p className="mt-1 text-sm text-muted-foreground">Vendor yang terpilih akan dipakai untuk seluruh item pada PO internal ini.</p>
            </div>
          </div>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          {vendorCatalog.map((vendor) => {
            const active = vendor.id === selectedVendorId;

            return (
              <button
                key={vendor.id}
                type="button"
                onClick={() => {
                  if (isEditable) {
                    setSelectedVendorId(vendor.id);
                  }
                }}
                disabled={!isEditable}
                className={cn(
                  "rounded-3xl border p-4 text-left transition",
                  active ? "border-primary bg-primary/5 shadow-sm" : "border-border/70 bg-background hover:bg-accent/40",
                  !isEditable && "cursor-not-allowed opacity-70",
                )}
              >
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="font-semibold text-foreground">{vendor.name}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{vendor.specialty}</p>
                  </div>
                  <Badge label={getVendorVerificationStatusLabel(vendor.verificationStatus)} className={getVendorVerificationStatusClass(vendor.verificationStatus)} />
                </div>
                <div className="mt-4 space-y-1 text-xs text-muted-foreground">
                  <p>PIC: {vendor.pic}</p>
                  <p>Phone: {vendor.phone}</p>
                  <p>Email: {vendor.email}</p>
                </div>
              </button>
            );
          })}
        </CardContent>
      </Card>

      {selectedVendor ? (
        <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">Vendor yang dipilih</p>
                <div className="mt-2 text-lg font-semibold tracking-tight">{selectedVendor.name}</div>
                <p className="mt-1 text-sm text-muted-foreground">{selectedVendor.specialty}</p>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-100 text-blue-700">
                <PackageIcon 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">PIC</p>
                  <p className="mt-0.5 text-sm font-semibold text-foreground">{selectedVendor.pic}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Verification</p>
                  <div className="mt-1">
                    <Badge
                      label={getVendorVerificationStatusLabel(selectedVendor.verificationStatus)}
                      className={getVendorVerificationStatusClass(selectedVendor.verificationStatus)}
                    />
                  </div>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Phone</p>
                  <p className="mt-0.5 text-sm font-semibold text-foreground">{selectedVendor.phone}</p>
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Email</p>
                  <p className="mt-0.5 text-sm font-semibold text-foreground">{selectedVendor.email}</p>
                </div>
              </div>
            </div>
            <div className="pt-3">
              <div className="flex items-start gap-2 text-sm text-muted-foreground">
                <ShieldCheckIcon className="mt-0.5 h-4 w-4 shrink-0" />
                <span>{selectedVendor.notes}</span>
              </div>
            </div>
          </div>
        </Card>
      ) : null}

      <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">Item PO Internal</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..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                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">
            {[
              { 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 = items.filter(
                (item) => item.category === section.key && (searchQuery === "" || item.itemName.toLowerCase().includes(searchQuery.toLowerCase())),
              );

              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 PR</th>
                                <th className="w-[18%] border-b border-border/70 px-3 py-2 font-medium text-right">Requested Amount</th>
                                <th className="w-[22%] border-b border-border/70 px-3 py-2 font-medium text-right">PO Amount</th>
                                <th className="w-[24%] border-b border-border/70 px-3 py-2 font-medium">Notes</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.poAmount);
                                const amountError = item.selected && (amount <= 0 || amount > item.requestedAmount);

                                return (
                                  <tr
                                    key={item.purchaseRequestItemId}
                                    className={cn("cursor-pointer transition hover:bg-accent/30", item.selected && "bg-primary/5")}
                                    onClick={() => handleToggleSelected(item.purchaseRequestItemId)}
                                  >
                                    <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">
                                      <div className="font-medium text-foreground">{formatVendorPoMoney(item.requestedAmount)}</div>
                                      <p className="mt-0.5 text-xs text-muted-foreground">Batas maksimum dari PR</p>
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top text-right">
                                      <input
                                        value={item.poAmount}
                                        onChange={(event) => updatePoAmount(item.purchaseRequestItemId, 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 requested amount.</p> : null}
                                    </td>
                                    <td className="border-b border-border/30 px-3 py-3 align-top">
                                      <input
                                        value={item.notes}
                                        onChange={(event) => updateItemNotes(item.purchaseRequestItemId, 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.purchaseRequestItemId)}
                                        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">{selectedItems.length} 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">{formatVendorPoMoney(totalRequested)}</p>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Total PO</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{formatVendorPoMoney(totalPoAmount)}</p>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">PO number</p>
              <p className="mt-0.5 text-lg font-bold text-foreground">{currentRecord?.poNumber ?? getNextVendorPoNumber()}</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
                  : "PR wajib berstatus collected. Nilai PO per item tidak boleh melebihi requested amount dari PR."}
              </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">
              PO ini sudah diproses. Gunakan detail page untuk melihat approval trail atau status issue.
            </div>
          ) : null}

          <div className="space-y-2">
            <label className="text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">Notes</label>
            <textarea
              rows={4}
              value={notes}
              onChange={(event) => setNotes(event.target.value)}
              disabled={!isEditable}
              placeholder="Catatan internal, hasil negosiasi, atau referensi approval..."
              className="w-full rounded-3xl 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 disabled:cursor-not-allowed disabled:bg-muted/40"
            />
          </div>

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

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