"use client";

import { useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { Trash2 } from "lucide-react";

import { useLocale } from "@/components/providers/locale-provider";
import { EmptyState, StatCard } from "@/components/shared/ops-primitives";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type { ConsignmentCandidateLot, ConsignmentDetail, ConsignmentListItem } from "@/types/consignment";
import type { Buyer } from "@/features/buyers/types/buyer";
import type { SalesRecord } from "@/types/master-data";
import { formatCurrencyAmount, formatDecimal } from "@/lib/formatters";

type CreateLineForm = {
  lot_id: string;
  qty_consigned: string;
  notes: string;
};

type CreateForm = {
  consignment_date: string;
  sales_id: string;
  buyer_id: string;
  notes: string;
  lines: CreateLineForm[];
};

type CloseLineForm = {
  close_date: string;
  selling_price: string;
  qty_sold: string;
  qty_returned: string;
  sales_commission: string;
};

const newCreateLine = (): CreateLineForm => ({
  lot_id: "",
  qty_consigned: "",
  notes: ""
});

const emptyCreateForm = (): CreateForm => ({
  consignment_date: new Date().toISOString().slice(0, 10),
  sales_id: "",
  buyer_id: "",
  notes: "",
  lines: [newCreateLine()]
});

function getStatusChip(status: string) {
  if (status === "OPEN") return "ops-chip-warning";
  if (status === "PARTIAL_CLOSED") return "ops-chip-muted";
  if (status === "CLOSED") return "ops-chip-active";
  return "ops-chip-muted";
}

function createDefaultCloseForm(): CloseLineForm {
  return {
    close_date: new Date().toISOString().slice(0, 10),
    selling_price: "0",
    qty_sold: "",
    qty_returned: "",
    sales_commission: "0"
  };
}

type ConsignmentsClientProps = {
  currencyCode: string;
};

export function ConsignmentsClient({ currencyCode }: ConsignmentsClientProps) {
  const { locale, dict } = useLocale();
  const searchParams = useSearchParams();
  const requestedId = searchParams.get("id");
  const [items, setItems] = useState<ConsignmentListItem[]>([]);
  const [salesList, setSalesList] = useState<SalesRecord[]>([]);
  const [buyers, setBuyers] = useState<Buyer[]>([]);
  const [lots, setLots] = useState<ConsignmentCandidateLot[]>([]);
  const [form, setForm] = useState<CreateForm>(emptyCreateForm);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<ConsignmentDetail | null>(null);
  const [closeForms, setCloseForms] = useState<Record<string, CloseLineForm>>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [closingLineId, setClosingLineId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function loadAll(preferredId?: string) {
    setLoading(true);
    setError(null);
    try {
      const [listRes, bootstrapRes] = await Promise.all([
        fetch("/api/v1/consignments", { cache: "no-store" }),
        fetch("/api/v1/consignments/bootstrap", { cache: "no-store" })
      ]);

      const listPayload = (await listRes.json()) as { data: ConsignmentListItem[] } | ApiErrorResponse;
      const bootstrapPayload = (await bootstrapRes.json()) as {
        data: {
          sales: SalesRecord[];
          buyers: Buyer[];
          lots: ConsignmentCandidateLot[];
        };
      } | ApiErrorResponse;

      if (!listRes.ok || !("data" in listPayload)) {
        throw new Error("message" in listPayload ? listPayload.message : "Gagal memuat titip jual.");
      }
      if (!bootstrapRes.ok || !("data" in bootstrapPayload)) {
        throw new Error("message" in bootstrapPayload ? bootstrapPayload.message : "Gagal memuat referensi titip jual.");
      }

      setItems(listPayload.data);
      setSalesList(bootstrapPayload.data.sales);
      setBuyers(bootstrapPayload.data.buyers);
      setLots(bootstrapPayload.data.lots);

      const nextId = preferredId ?? selectedId ?? listPayload.data[0]?.id ?? null;
      setSelectedId(nextId);
      if (nextId) {
        await openDetail(nextId);
      } else {
        setDetail(null);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat titip jual.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadAll(requestedId ?? undefined);
  }, [requestedId]);

  async function openDetail(id: string) {
    setDetailLoading(true);
    setError(null);
    try {
      const response = await fetch(`/api/v1/consignments/${id}`, { cache: "no-store" });
      const payload = (await response.json()) as DetailResponse<ConsignmentDetail> | ApiErrorResponse;

      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : "Gagal memuat detail titip jual.");
      }

      setSelectedId(id);
      setDetail(payload.data);
      setCloseForms(() =>
        payload.data.lines
          .filter((line) => line.status !== "CLOSED")
          .reduce<Record<string, CloseLineForm>>((acc, line) => {
            acc[line.id] = createDefaultCloseForm();
            return acc;
          }, {})
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat detail titip jual.");
    } finally {
      setDetailLoading(false);
    }
  }

  function patchForm<K extends keyof CreateForm>(key: K, value: CreateForm[K]) {
    setForm((current) => ({ ...current, [key]: value }));
  }

  function updateLine(index: number, patch: Partial<CreateLineForm>) {
    setForm((current) => ({
      ...current,
      lines: current.lines.map((line, currentIndex) =>
        currentIndex === index ? { ...line, ...patch } : line
      )
    }));
  }

  function addLine() {
    setForm((current) => ({
      ...current,
      lines: [...current.lines, newCreateLine()]
    }));
  }

  function removeLine(index: number) {
    setForm((current) => ({
      ...current,
      lines: current.lines.length === 1 ? current.lines : current.lines.filter((_, currentIndex) => currentIndex !== index)
    }));
  }

  async function saveConsignment() {
    setSaving(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/consignments", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          consignment_date: form.consignment_date,
          sales_id: form.sales_id,
          buyer_id: form.buyer_id,
          notes: form.notes || null,
          lines: form.lines.map((line) => ({
            lot_id: line.lot_id,
            qty_consigned: Number(line.qty_consigned),
            notes: line.notes || null
          }))
        })
      });

      const payload = (await response.json()) as DetailResponse<ConsignmentDetail> | ApiErrorResponse;
      if (!response.ok) {
        const validationMessage =
          "errors" in payload && payload.errors
            ? Object.values(payload.errors)[0]?.[0]
            : null;
        throw new Error(validationMessage ?? ("message" in payload ? payload.message : "Gagal menyimpan titip jual."));
      }
      if (!("data" in payload)) {
        throw new Error("Gagal menyimpan titip jual.");
      }

      setForm(emptyCreateForm());
      await loadAll(payload.data.id);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menyimpan titip jual.");
    } finally {
      setSaving(false);
    }
  }

  function patchCloseForm(lineId: string, patch: Partial<CloseLineForm>) {
    setCloseForms((current) => ({
      ...current,
      [lineId]: {
        ...(current[lineId] ?? createDefaultCloseForm()),
        ...patch
      }
    }));
  }

  async function closeLine(lineId: string) {
    const lineForm = closeForms[lineId];
    if (!lineForm) return;

    setClosingLineId(lineId);
    setError(null);
    try {
      const response = await fetch(`/api/v1/consignments/lines/${lineId}/close`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          close_date: lineForm.close_date,
          selling_price: Number(lineForm.selling_price || 0),
          qty_sold: Number(lineForm.qty_sold || 0),
          qty_returned: Number(lineForm.qty_returned || 0),
          sales_commission: Number(lineForm.sales_commission || 0)
        })
      });

      const payload = (await response.json()) as { success: true } | ApiErrorResponse;
      if (!response.ok) {
        const validationMessage =
          "errors" in payload && payload.errors
            ? Object.values(payload.errors)[0]?.[0]
            : null;
        throw new Error(validationMessage ?? ("message" in payload ? payload.message : "Gagal menutup item titip jual."));
      }

      if (selectedId) {
        await loadAll(selectedId);
      } else {
        await loadAll();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menutup item titip jual.");
    } finally {
      setClosingLineId(null);
    }
  }

  const selectedSales = salesList.find((sales) => sales.id === form.sales_id) ?? null;
  const selectedBuyer = buyers.find((buyer) => buyer.id === form.buyer_id) ?? null;
  const openLineCount = detail?.lines.filter((line) => line.status !== "CLOSED").length ?? 0;
  const totalConsignedQty = detail?.lines.reduce((sum, line) => sum + line.qty_consigned, 0) ?? 0;
  const totalReturnedQty = detail?.lines.reduce((sum, line) => sum + line.qty_returned, 0) ?? 0;
  const totalSoldQty = detail?.lines.reduce((sum, line) => sum + line.qty_sold, 0) ?? 0;

  return (
    <section className="space-y-6">
      {detail ? (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <StatCard label={locale === "id" ? "Titip Jual" : "Consignment"} value={detail.consignment_no} hint={locale === "id" ? `${detail.sales.name} ke ${detail.buyer.name}` : `${detail.sales.name} to ${detail.buyer.name}`} />
          <StatCard label={locale === "id" ? "Status" : "Status"} value={detail.status} hint={locale === "id" ? `${openLineCount} item belum selesai` : `${openLineCount} items still open`} tone={detail.status === "CLOSED" ? "teal" : "default"} />
          <StatCard label={dict.consignments.consignedWeight} value={formatDecimal(totalConsignedQty, locale)} hint={locale === "id" ? "Total seluruh item" : "Total of all items"} />
          <StatCard label={`${dict.consignments.soldWeight} / ${dict.consignments.returnedWeight}`} value={`${formatDecimal(totalSoldQty, locale)} / ${formatDecimal(totalReturnedQty, locale)}`} hint={locale === "id" ? "Akumulasi hasil close" : "Accumulated closing results"} />
        </div>
      ) : null}

      <div className="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
        <div className="ops-card p-6">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="ops-overline">{dict.consignments.overline}</p>
              <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">{dict.consignments.title}</h2>
              <p className="mt-3 text-[13px] leading-6 text-slate-500">
                {dict.consignments.helper}
              </p>
            </div>
            <button type="button" onClick={() => setForm(emptyCreateForm())} className="ops-btn-secondary">
              {dict.common.formReset}
            </button>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-2">
            <Field label={dict.consignments.code} value={dict.consignments.codeAuto} readOnly />
            <Field
              label={dict.consignments.consignmentDate}
              value={form.consignment_date}
              onChange={(value) => patchForm("consignment_date", value)}
              type="date"
            />
            <SelectField
              label={dict.consignments.sales}
              value={form.sales_id}
              onChange={(value) => patchForm("sales_id", value)}
              options={salesList.map((sales) => ({
                value: sales.id,
                label: `${sales.code} - ${sales.name}`
              }))}
              placeholder={dict.consignments.chooseSales}
            />
            <SelectField
              label={dict.consignments.buyer}
              value={form.buyer_id}
              onChange={(value) => patchForm("buyer_id", value)}
              options={buyers.map((buyer) => ({
                value: buyer.id,
                label: `${buyer.code} - ${buyer.name}`
              }))}
              placeholder={dict.consignments.chooseBuyer}
            />
          </div>

          {(selectedSales || selectedBuyer) ? (
            <div className="mt-4 grid gap-4 md:grid-cols-2">
              <InfoCard label={dict.consignments.sales} value={selectedSales ? `${selectedSales.code} · ${selectedSales.name}` : "-"} />
              <InfoCard label={dict.consignments.buyer} value={selectedBuyer ? `${selectedBuyer.code} · ${selectedBuyer.name}` : "-"} />
            </div>
          ) : null}

          <label className="mt-5 block">
            <span className="ops-label">{locale === "id" ? "Catatan" : "Notes"}</span>
            <textarea
              value={form.notes}
              onChange={(event) => patchForm("notes", event.target.value)}
              rows={3}
              className="ops-textarea"
            />
          </label>

          <div className="mt-6 rounded-xl border border-line/70 bg-slate-50/70 p-4">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="ops-title">{dict.consignments.soldItems}</p>
                <p className="ops-copy">{dict.consignments.soldItemsCopy}</p>
              </div>
              <button type="button" onClick={addLine} className="ops-btn-secondary">
                {dict.consignments.addProduct}
              </button>
            </div>

            <div className="mt-4 space-y-4">
              {form.lines.map((line, index) => {
                const selectedLot = lots.find((lot) => lot.lot_id === line.lot_id) ?? null;
                const selectedLotIds = form.lines.map((row) => row.lot_id).filter(Boolean);
                const allowedLots = lots.filter((lot) => lot.lot_id === line.lot_id || !selectedLotIds.includes(lot.lot_id));
                return (
                  <div key={`${index}-${line.lot_id || "new"}`} className="rounded-lg border border-line/70 bg-white p-4">
                    <div className="grid gap-3 lg:grid-cols-[minmax(0,1.25fr)_minmax(0,0.8fr)_56px]">
                      <SelectField
                        label={locale === "id" ? "Lot" : "Lot"}
                        value={line.lot_id}
                        onChange={(value) => updateLine(index, { lot_id: value, qty_consigned: "" })}
                        options={allowedLots.map((lot) => ({
                          value: lot.lot_id,
                          label: `${lot.lot_code} · ${lot.grade}`
                        }))}
                        placeholder={locale === "id" ? "Pilih lot aktif" : "Choose active lot"}
                      />
                      <Field
                        label={dict.consignments.consignedWeight}
                        value={line.qty_consigned}
                        onChange={(value) => updateLine(index, { qty_consigned: value })}
                        placeholder={selectedLot ? `Max ${selectedLot.available_qty}` : "0.000"}
                      />
                      <div className="flex items-end">
                        {index === 0 ? (
                          <div className="h-11 w-full" />
                        ) : (
                          <button
                            type="button"
                            onClick={() => removeLine(index)}
                            className="inline-flex h-11 w-11 items-center justify-center rounded-xl border border-line/70 bg-white text-slate-500 transition hover:border-ember/30 hover:bg-ember/5 hover:text-ember"
                            aria-label={locale === "id" ? "Hapus baris" : "Remove row"}
                            title={locale === "id" ? "Hapus baris" : "Remove row"}
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        )}
                      </div>
                    </div>

                    {selectedLot ? (
                      <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
                        <CompactInfoCard label={locale === "id" ? "Grade" : "Grade"} value={selectedLot.grade} />
                        <CompactInfoCard label={locale === "id" ? "Kode lot" : "Lot code"} value={selectedLot.lot_code} />
                        <CompactInfoCard label={dict.consignments.currentWeight} value={`${formatDecimal(selectedLot.available_qty, locale)} ${selectedLot.unit_code}`} />
                        <CompactInfoCard
                          label={locale === "id" ? "Harga MAL" : "MAL Price"}
                          value={
                            selectedLot.mal_unit_price === null
                              ? "-"
                              : formatCurrencyAmount(selectedLot.mal_unit_price, locale, currencyCode, 0)
                          }
                        />
                      </div>
                    ) : null}

                    <label className="mt-4 block">
                      <span className="ops-label">{dict.consignments.itemNotes}</span>
                      <textarea
                        value={line.notes}
                        onChange={(event) => updateLine(index, { notes: event.target.value })}
                        rows={2}
                        className="ops-textarea min-h-[84px]"
                      />
                    </label>
                  </div>
                );
              })}
            </div>
          </div>

          {error ? (
            <div className="mt-5 rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">{error}</div>
          ) : null}

          <div className="mt-6 flex justify-end">
            <button type="button" onClick={() => void saveConsignment()} className="ops-btn-primary" disabled={saving}>
              {saving ? dict.common.processing : dict.consignments.saveLabel}
            </button>
          </div>
        </div>

        <div className="space-y-6">
          <div className="ops-table-shell">
            <div className="ops-section-head">
              <div>
                <p className="ops-title">{dict.consignments.listTitle}</p>
                <p className="ops-copy">{dict.consignments.listCopy}</p>
              </div>
              <div className="ops-chip-muted">{items.length} {locale === "id" ? "transaksi" : "transactions"}</div>
            </div>

            {loading ? (
              <div className="px-6 py-8 text-sm text-ink/60">{locale === "id" ? "Memuat data..." : "Loading data..."}</div>
            ) : items.length === 0 ? (
              <EmptyState title={dict.consignments.noData} copy={dict.consignments.noDataCopy} />
            ) : (
              <div className="overflow-x-auto">
                <table className="ops-table">
                  <thead>
                    <tr>
                      <th>{dict.consignments.code}</th>
                      <th>{dict.consignments.salesBuyer}</th>
                      <th>{locale === "id" ? "Status" : "Status"}</th>
                      <th>{dict.consignments.qty}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {items.map((item) => (
                      <tr
                        key={item.id}
                        className={selectedId === item.id ? "bg-moss/5" : undefined}
                        onClick={() => void openDetail(item.id)}
                      >
                        <td className="font-semibold text-ink">{item.consignment_no}</td>
                        <td>
                          <div className="font-medium text-ink">{item.sales.name}</div>
                          <div className="text-xs text-slate-500">{item.buyer.name}</div>
                        </td>
                        <td>
                          <span className={getStatusChip(item.status)}>{item.status}</span>
                        </td>
                        <td>{formatDecimal(item.total_qty_consigned, locale)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {detailLoading ? (
            <div className="ops-card p-6 text-sm text-ink/60">{dict.consignments.detailLoading}</div>
          ) : !detail ? (
            <div className="ops-card p-6 text-sm text-ink/60">{dict.consignments.detailEmpty}</div>
          ) : (
            <div className="ops-card p-6">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="ops-overline">{dict.consignments.closingTitle}</p>
                  <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">{detail.consignment_no}</h2>
                  <p className="mt-2 text-sm text-slate-500">
                    {detail.sales.name} · {detail.buyer.name} · {new Date(detail.consignment_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")}
                  </p>
                </div>
                <span className={getStatusChip(detail.status)}>{detail.status}</span>
              </div>

              <div className="mt-6 space-y-5">
                {detail.lines.map((line) => {
                  const closeForm = closeForms[line.id] ?? createDefaultCloseForm();
                  const qtySold = Number(closeForm.qty_sold || 0);
                  const qtyReturned = Number(closeForm.qty_returned || 0);
                  const salesCommission = Number(closeForm.sales_commission || 0);
                  const derivedShrinkage = Math.max(0, Number((line.qty_consigned - qtySold - qtyReturned).toFixed(3)));
                  const malUnitPrice = line.mal_unit_price_snapshot ?? 0;
                  const shareAgent = line.agent_share_percent ?? 0;
                  const derivedAgentCommission = Number(
                    ((((qtySold * (Number(closeForm.selling_price || 0) - malUnitPrice)) - salesCommission) * shareAgent) / 100).toFixed(2)
                  );

                  return (
                    <div key={line.id} className="rounded-lg border border-line/70 bg-slate-50/60 p-4">
                      <div className="flex items-start justify-between gap-4">
                        <div>
                          <div className="font-semibold text-ink">{line.lot_code}</div>
                          <div className="mt-1 text-sm text-slate-500">
                            {line.grade} · {formatDecimal(line.qty_consigned, locale)} {line.unit_code}
                          </div>
                        </div>
                        <span className={getStatusChip(line.status)}>{line.status}</span>
                      </div>

                      <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-5">
                        <CompactInfoCard label={dict.consignments.currentWeight} value={`${formatDecimal(line.available_qty_snapshot, locale)} ${line.unit_code}`} />
                        <CompactInfoCard label={locale === "id" ? "Harga MAL" : "MAL Price"} value={line.mal_unit_price_snapshot === null ? "-" : formatCurrencyAmount(line.mal_unit_price_snapshot, locale, currencyCode, 0)} />
                        <CompactInfoCard label={locale === "id" ? "Gudang" : "Warehouse"} value={line.warehouse} />
                        <CompactInfoCard label={dict.consignments.currentAvailable} value={`${formatDecimal(line.current_available_qty, locale)} ${line.unit_code}`} />
                        <CompactInfoCard
                          label={locale === "id" ? "Bagi hasil agen" : "Agent profit share"}
                          value={
                            line.agent_share_percent
                              ? `${line.agent_name_snapshot ?? (locale === "id" ? "Agen" : "Agent")} · ${formatDecimal(line.agent_share_percent, locale, 2)}%`
                              : "-"
                          }
                        />
                      </div>

                      {line.status === "CLOSED" ? (
                        <div className="mt-4 space-y-3">
                          <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-6">
                            <CompactInfoCard label={locale === "id" ? "Tanggal tutup" : "Close date"} value={line.close_date ?? "-"} />
                            <CompactInfoCard label={dict.consignments.soldPrice} value={line.selling_price === null ? "-" : formatCurrencyAmount(line.selling_price, locale, currencyCode, 0)} />
                            <CompactInfoCard label={dict.consignments.soldWeight} value={formatDecimal(line.qty_sold, locale)} />
                            <CompactInfoCard label={dict.consignments.returnedWeight} value={formatDecimal(line.qty_returned, locale)} />
                            <CompactInfoCard label={dict.consignments.salesCommission} value={formatCurrencyAmount(line.sales_commission, locale, currencyCode, 0)} />
                            <CompactInfoCard label={dict.consignments.shrinkageAgentCommission} value={`${formatDecimal(line.qty_shrinkage, locale)} / ${formatCurrencyAmount(line.agent_commission, locale, currencyCode, 0)}`} />
                          </div>
                          <div className="rounded border border-line/70 bg-white px-4 py-3 text-xs leading-6 text-slate-600">
                            Rumus komisi agen:
                            {" "}
                            <span className="font-semibold text-ink">
                              ((berat terjual * (harga jual - harga MAL)) - komisi sales) * persen bagi hasil agen
                            </span>
                            {line.agent_share_percent ? null : (
                              <span className="text-slate-500">. Nilai saat ini `0` karena lot ini tidak punya data agent share.</span>
                            )}
                          </div>
                        </div>
                      ) : (
                        <div className="mt-4">
                          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
                            <Field label="Tanggal close" value={closeForm.close_date} onChange={(value) => patchCloseForm(line.id, { close_date: value })} type="date" />
                            <Field label="Harga jual" value={closeForm.selling_price} onChange={(value) => patchCloseForm(line.id, { selling_price: value })} />
                            <Field label="Berat terjual" value={closeForm.qty_sold} onChange={(value) => patchCloseForm(line.id, { qty_sold: value })} />
                            <Field label="Berat kembali" value={closeForm.qty_returned} onChange={(value) => patchCloseForm(line.id, { qty_returned: value })} />
                            <Field label="Komisi sales" value={closeForm.sales_commission} onChange={(value) => patchCloseForm(line.id, { sales_commission: value })} />
                          </div>
                          <div className="mt-3 grid gap-3 md:grid-cols-2">
                            <div className="rounded border border-line/70 bg-white px-4 py-3 text-sm text-slate-600">
                              {dict.consignments.autoShrinkage} <span className="font-semibold text-ink">{formatDecimal(derivedShrinkage, locale)} {line.unit_code}</span>
                            </div>
                            <div className="rounded border border-line/70 bg-white px-4 py-3 text-sm text-slate-600">
                              Komisi agen otomatis:
                              {" "}
                              <span className="font-semibold text-ink">{formatCurrencyAmount(derivedAgentCommission, locale, currencyCode, 0)}</span>
                              {line.agent_share_percent ? (
                                <span className="text-slate-500">
                                  {" "}
                                  ({line.agent_name_snapshot ?? "Agen"} · {formatDecimal(line.agent_share_percent, locale, 2)}%)
                                </span>
                              ) : (
                                <span className="text-slate-500"> (tidak ada bagi hasil agen)</span>
                              )}
                            </div>
                          </div>
                          <div className="mt-3 rounded border border-line/70 bg-white px-4 py-3 text-xs leading-6 text-slate-600">
                            Rumus komisi agen:
                            {" "}
                            <span className="font-semibold text-ink">
                              ((berat terjual * (harga jual - harga MAL)) - komisi sales) * persen bagi hasil agen
                            </span>
                          </div>
                          <div className="mt-4 flex justify-end">
                            <button
                              type="button"
                              onClick={() => void closeLine(line.id)}
                              className="ops-btn-primary"
                              disabled={closingLineId === line.id}
                            >
                              {closingLineId === line.id ? "Menyimpan..." : "Tutup item"}
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  placeholder,
  readOnly = false
}: {
  label: string;
  value: string;
  onChange?: (value: string) => void;
  type?: string;
  placeholder?: string;
  readOnly?: boolean;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <input
        value={value}
        onChange={(event) => onChange?.(event.target.value)}
        type={type}
        placeholder={placeholder}
        readOnly={readOnly}
        className={`ops-input ${readOnly ? "bg-slate-50 text-slate-600" : ""}`}
      />
    </label>
  );
}

function SelectField({
  label,
  value,
  onChange,
  options,
  placeholder
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Array<{ value: string; label: string }>;
  placeholder: string;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <select value={value} onChange={(event) => onChange(event.target.value)} className="ops-select">
        <option value="">{placeholder}</option>
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </label>
  );
}

function InfoCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded border border-line/70 bg-white px-4 py-3">
      <p className="ops-overline">{label}</p>
      <p className="mt-2 text-[14px] font-medium text-ink">{value}</p>
    </div>
  );
}

function CompactInfoCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-line/70 bg-slate-50/60 px-3 py-2.5">
      <p className="text-[10px] font-bold uppercase tracking-[0.05em] text-slate-500">{label}</p>
      <p className="mt-1.5 text-[13px] font-medium leading-5 text-ink break-words">{value}</p>
    </div>
  );
}
