"use client";

import { useEffect, useMemo, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { EmptyState, StatCard } from "@/components/shared/ops-primitives";
import { formatCurrencyAmount } from "@/lib/formatters";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type {
  PurchaseAnalysisDetail,
  PurchaseAnalysisListItem
} from "@/types/purchase-analysis";

type CostEntryForm = {
  id?: string;
  cost_type: string;
  description: string;
  amount: string;
};

type AnalysisForm = {
  status: "DRAFT" | "FINAL";
  weight_buy: string;
  weight_received: string;
  weight_final: string;
  weight_gain_percent: string;
  shrinkage_delta: string;
  moisture_buy_percent: string;
  moisture_received_percent: string;
  moisture_final_percent: string;
  above_average_ratio_percent: string;
  mk_percent: string;
  non_mk_percent: string;
  average_price: string;
  modal_beli: string;
  modal_masuk: string;
  modal_jual: string;
  modal_barang: string;
  total_modal_beli: string;
  total_modal_mal: string;
  market_reference_price: string;
  market_valuation_total: string;
  agent_profit_share_total: string;
  notes: string;
  cost_entries: CostEntryForm[];
};

const emptyCostEntry = (): CostEntryForm => ({
  cost_type: "",
  description: "",
  amount: ""
});

const emptyForm: AnalysisForm = {
  status: "DRAFT",
  weight_buy: "",
  weight_received: "",
  weight_final: "",
  weight_gain_percent: "",
  shrinkage_delta: "",
  moisture_buy_percent: "",
  moisture_received_percent: "",
  moisture_final_percent: "",
  above_average_ratio_percent: "",
  mk_percent: "",
  non_mk_percent: "",
  average_price: "",
  modal_beli: "",
  modal_masuk: "",
  modal_jual: "",
  modal_barang: "",
  total_modal_beli: "",
  total_modal_mal: "",
  market_reference_price: "",
  market_valuation_total: "",
  agent_profit_share_total: "0",
  notes: "",
  cost_entries: []
};

function toInput(value: number | null) {
  return value === null ? "" : String(value);
}

function fromNullableNumber(value: string) {
  if (value.trim() === "") return null;
  return Number(value);
}

function formatNumber(value: number | null, locale: string, digits = 2) {
  if (value === null) return "-";
  return value.toLocaleString(locale === "id" ? "id-ID" : "en-US", {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits
  });
}

function formatCurrency(value: number | null, locale: string, currencyCode: string) {
  if (value === null) return "-";
  return formatCurrencyAmount(value, locale, currencyCode, 2);
}

async function parseJsonResponse<T>(response: Response, context: string): Promise<T> {
  const responseText = await response.text();
  if (responseText.trim().length === 0) {
    throw new Error(`${context}: respons kosong (${response.status} ${response.url})`);
  }

  try {
    return JSON.parse(responseText) as T;
  } catch {
    const preview = responseText.slice(0, 160);
    throw new Error(
      `${context}: server mengembalikan data non-JSON (${response.status} ${response.url}) ${preview}`
    );
  }
}

function mapDetailToForm(detail: PurchaseAnalysisDetail): AnalysisForm {
  return {
    status: detail.inputs.status === "FINAL" ? "FINAL" : "DRAFT",
    weight_buy: toInput(detail.summary.berat_beli),
    weight_received: toInput(detail.summary.berat_masuk),
    weight_final: toInput(detail.summary.berat_akhir),
    weight_gain_percent: toInput(detail.summary.berat_naik_percent),
    shrinkage_delta: toInput(detail.summary.susut_tambah),
    moisture_buy_percent: toInput(detail.summary.kadar_beli_percent),
    moisture_received_percent: toInput(detail.summary.kadar_masuk_percent),
    moisture_final_percent: toInput(detail.summary.kadar_akhir_percent),
    above_average_ratio_percent: toInput(detail.summary.barang_atas_rata2_percent),
    mk_percent: toInput(detail.summary.mk_percent),
    non_mk_percent: toInput(detail.summary.non_mk_percent),
    average_price: toInput(detail.summary.harga_rata2),
    modal_beli: toInput(detail.summary.modal_beli),
    modal_masuk: toInput(detail.summary.modal_masuk),
    modal_jual: toInput(detail.summary.modal_jual),
    modal_barang: toInput(detail.summary.modal_barang),
    total_modal_beli: toInput(detail.summary.total_modal_beli),
    total_modal_mal: toInput(detail.summary.total_modal_mal),
    market_reference_price: toInput(detail.summary.harga_mk_ar),
    market_valuation_total: toInput(detail.summary.total_modal_mal),
    agent_profit_share_total: String(detail.summary.laba_rugi_agen),
    notes: detail.inputs.notes ?? "",
    cost_entries:
      detail.inputs.cost_entries.length > 0
        ? detail.inputs.cost_entries.map((entry) => ({
            id: entry.id,
            cost_type: entry.cost_type,
            description: entry.description ?? "",
            amount: String(entry.amount)
          }))
        : [emptyCostEntry()]
  };
}

type PurchaseAnalysisClientProps = {
  currencyCode: string;
};

export function PurchaseAnalysisClient({ currencyCode }: PurchaseAnalysisClientProps) {
  const { locale, dict } = useLocale();
  const [items, setItems] = useState<PurchaseAnalysisListItem[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<PurchaseAnalysisDetail | null>(null);
  const [form, setForm] = useState<AnalysisForm>(emptyForm);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function loadList(preferredId?: string) {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/purchase-analyses", { cache: "no-store" });
      const payload = await parseJsonResponse<{ data: PurchaseAnalysisListItem[] } | ApiErrorResponse>(
        response,
        "Memuat daftar analisis"
      );
      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : "Gagal memuat analisis pembelian");
      }
      setItems(payload.data);
      const nextId = preferredId ?? selectedId ?? payload.data[0]?.purchase_id ?? null;
      setSelectedId(nextId);
      if (nextId) {
        await openDetail(nextId);
      } else {
        setDetail(null);
        setForm(emptyForm);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat analisis pembelian");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadList();
  }, []);

  async function openDetail(purchaseId: string) {
    setDetailLoading(true);
    setError(null);
    try {
      const response = await fetch(`/api/v1/purchase-analyses/${purchaseId}`, {
        cache: "no-store"
      });
      const payload = await parseJsonResponse<
        DetailResponse<PurchaseAnalysisDetail> | ApiErrorResponse
      >(response, "Memuat detail analisis");
      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : "Gagal memuat detail analisis");
      }
      setSelectedId(purchaseId);
      setDetail(payload.data);
      setForm(mapDetailToForm(payload.data));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat detail analisis");
    } finally {
      setDetailLoading(false);
    }
  }

  async function saveAnalysis() {
    if (!selectedId) return;
    setSaving(true);
    setError(null);
    try {
      const response = await fetch(`/api/v1/purchase-analyses/${selectedId}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          status: form.status,
          weight_buy: fromNullableNumber(form.weight_buy),
          weight_received: fromNullableNumber(form.weight_received),
          weight_final: fromNullableNumber(form.weight_final),
          average_price: fromNullableNumber(form.average_price),
          modal_beli: fromNullableNumber(form.modal_beli),
          modal_masuk: fromNullableNumber(form.modal_masuk),
          modal_jual: fromNullableNumber(form.modal_jual),
          modal_barang: fromNullableNumber(form.modal_barang),
          total_modal_beli: fromNullableNumber(form.total_modal_beli),
          total_modal_mal: fromNullableNumber(form.total_modal_mal),
          moisture_buy_percent: fromNullableNumber(form.moisture_buy_percent),
          moisture_received_percent: fromNullableNumber(form.moisture_received_percent),
          moisture_final_percent: fromNullableNumber(form.moisture_final_percent),
          above_average_ratio_percent: fromNullableNumber(form.above_average_ratio_percent),
          market_reference_price: fromNullableNumber(form.market_reference_price),
          market_valuation_total: fromNullableNumber(form.market_valuation_total),
          agent_profit_share_total: Number(form.agent_profit_share_total || 0),
          notes: form.notes || null,
          cost_entries: form.cost_entries
            .filter(
              (entry) =>
                entry.cost_type.trim() !== "" ||
                entry.description.trim() !== "" ||
                entry.amount.trim() !== ""
            )
            .map((entry) => ({
              cost_type: entry.cost_type,
              description: entry.description || null,
              amount: Number(entry.amount || 0)
            }))
        })
      });

      const payload = await parseJsonResponse<
        DetailResponse<PurchaseAnalysisDetail> | ApiErrorResponse
      >(response, "Menyimpan analisis");
      if (!response.ok || !("data" in payload)) {
        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 analisis"));
      }

      setDetail(payload.data);
      setForm(mapDetailToForm(payload.data));
      await loadList(selectedId);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menyimpan analisis");
    } finally {
      setSaving(false);
    }
  }

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

  function updateCostEntry(index: number, patch: Partial<CostEntryForm>) {
    setForm((current) => ({
      ...current,
      cost_entries: current.cost_entries.map((entry, currentIndex) =>
        currentIndex === index ? { ...entry, ...patch } : entry
      )
    }));
  }

  function addCostEntry() {
    setForm((current) => ({
      ...current,
      cost_entries: [...current.cost_entries, emptyCostEntry()]
    }));
  }

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

  const summaryRows = useMemo(() => {
    if (!detail) return [];

    return [
      ["BERAT BELI", formatNumber(detail.summary.berat_beli, locale, 3)],
      ["BERAT MASUK", formatNumber(detail.summary.berat_masuk, locale, 3)],
      ["BERAT NAIK (%)", detail.summary.berat_naik_percent === null ? "-" : `${formatNumber(detail.summary.berat_naik_percent, locale)}%`],
      ["BERAT AKHIR", formatNumber(detail.summary.berat_akhir, locale, 3)],
      ["SUSUT/TAMBAH", formatNumber(detail.summary.susut_tambah, locale, 3)],
      ["KADAR MASUK", detail.summary.kadar_masuk_percent === null ? "-" : `${formatNumber(detail.summary.kadar_masuk_percent, locale)}%`],
      ["KADAR BELI", detail.summary.kadar_beli_percent === null ? "-" : `${formatNumber(detail.summary.kadar_beli_percent, locale)}%`],
      ["KADAR AKHIR", detail.summary.kadar_akhir_percent === null ? "-" : `${formatNumber(detail.summary.kadar_akhir_percent, locale)}%`],
      ["BRG ATAS RATA2", detail.summary.barang_atas_rata2_percent === null ? "-" : `${formatNumber(detail.summary.barang_atas_rata2_percent, locale)}%`],
      ["HARGA MK A/R", formatCurrency(detail.summary.harga_mk_ar, locale, currencyCode)],
      ["MODAL BELI", formatCurrency(detail.summary.modal_beli, locale, currencyCode)],
      ["MODAL MASUK", formatCurrency(detail.summary.modal_masuk, locale, currencyCode)],
      ["MODAL JUAL", formatCurrency(detail.summary.modal_jual, locale, currencyCode)],
      ["MODAL BARANG", formatCurrency(detail.summary.modal_barang, locale, currencyCode)],
      ["OPERASIONAL", formatCurrency(detail.summary.operasional, locale, currencyCode)],
      ["TOTAL MODAL BELI", formatCurrency(detail.summary.total_modal_beli, locale, currencyCode)],
      ["TOTAL MODAL MAL", formatCurrency(detail.summary.total_modal_mal, locale, currencyCode)],
      ["TOTAL LABA/RUGI", formatCurrency(detail.summary.total_laba_rugi, locale, currencyCode)],
      ["LABA/RUGI AGEN", formatCurrency(detail.summary.laba_rugi_agen, locale, currencyCode)],
      ["LABA TOTAL/kg", formatCurrency(detail.summary.laba_total_per_kg, locale, currencyCode)],
      ["LABA AGEN/kg", formatCurrency(detail.summary.laba_agen_per_kg, locale, currencyCode)]
    ];
  }, [currencyCode, detail, locale]);

  return (
    <section className="grid gap-6 xl:grid-cols-[0.92fr_1.08fr]">
      <div className="ops-card overflow-hidden">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.purchaseAnalysisModule.listTitle}</p>
            <p className="ops-copy">{dict.purchaseAnalysisModule.listCopy}</p>
          </div>
          <div className="ops-chip-muted whitespace-nowrap">{items.length} {dict.purchaseAnalysisModule.countSuffix}</div>
        </div>
        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.common.loading}</div>
        ) : items.length === 0 ? (
          <EmptyState
            title={dict.purchaseAnalysisModule.noData}
            copy={dict.purchaseAnalysisModule.noDataCopy}
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full text-left text-sm">
              <thead className="bg-slate-50 text-xs uppercase tracking-[0.08em] text-slate-500">
                <tr>
                  <th className="px-6 py-4">Pembelian</th>
                  <th className="px-4 py-4">Berat</th>
                  <th className="px-4 py-4">Laba/Rugi</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line/70">
                {items.map((item) => (
                  <tr
                    key={item.purchase_id}
                    className={selectedId === item.purchase_id ? "bg-moss/5" : "bg-white"}
                  >
                    <td className="px-6 py-4">
                      <button
                        type="button"
                        onClick={() => void openDetail(item.purchase_id)}
                        className="text-left"
                      >
                        <div className="font-semibold text-ink">{item.purchase_no}</div>
                        <div className="mt-1 text-xs text-slate-500">{item.supplier_name}</div>
                        <div className="mt-2 flex gap-2 text-[11px]">
                          <span className="ops-chip-muted">{item.purchase_status}</span>
                          <span className={item.analysis_status === "FINAL" ? "ops-chip-active" : "ops-chip-muted"}>
                            {item.analysis_status}
                          </span>
                        </div>
                      </button>
                    </td>
                    <td className="px-4 py-4 text-slate-600">
                      <div>Beli: {formatNumber(item.weight_buy, locale, 3)}</div>
                      <div className="mt-1">Akhir: {formatNumber(item.weight_final, locale, 3)}</div>
                    </td>
                    <td className="px-4 py-4 font-medium text-ink">
                      {formatCurrency(item.total_laba_rugi, locale, currencyCode)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="space-y-6">
        {error ? <div className="rounded border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}
        {detailLoading || !detail ? (
          <div className="ops-card p-6 text-sm text-ink/60">
            {detailLoading ? dict.purchaseAnalysisModule.loadingDetail : dict.purchaseAnalysisModule.emptyDetail}
          </div>
        ) : (
          <>
            <div className="grid gap-4 md:grid-cols-3">
              <StatCard label="Modal Barang" value={formatCurrency(detail.summary.modal_barang, locale, currencyCode)} hint={detail.purchase.purchase_no} />
              <StatCard label={dict.purchaseAnalysisModule.operational} value={formatCurrency(detail.summary.operasional, locale, currencyCode)} hint="Akumulasi cost entries" />
              <StatCard
                label={dict.purchaseAnalysisModule.profitLoss}
                value={formatCurrency(detail.summary.total_laba_rugi, locale, currencyCode)}
                hint={detail.inputs.status === "FINAL" ? dict.purchaseAnalysisModule.finalAnalysis : dict.purchaseAnalysisModule.draftAnalysis}
                tone={detail.summary.total_laba_rugi !== null && detail.summary.total_laba_rugi < 0 ? "danger" : "default"}
              />
            </div>

            <div className="ops-card p-6">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="ops-overline">{dict.purchaseAnalysisModule.overline}</p>
                  <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">{detail.purchase.purchase_no}</h2>
                  <p className="mt-2 text-sm text-slate-500">
                    {detail.purchase.supplier_name} · {new Date(detail.purchase.purchase_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")} · {dict.purchaseAnalysisModule.totalPurchase} {formatCurrency(detail.purchase.grand_total, locale, currencyCode)}
                  </p>
                </div>
                <select
                  value={form.status}
                  onChange={(event) => patchForm("status", event.target.value as AnalysisForm["status"])}
                  className="ops-select w-[160px]"
                >
                  <option value="DRAFT">Draft</option>
                  <option value="FINAL">Final</option>
                </select>
              </div>

              <div className="mt-6 grid gap-4 md:grid-cols-3">
                <MetricField
                  label="Berat beli"
                  actual={detail.actuals.weight_buy}
                  value={form.weight_buy}
                  onChange={(value) => patchForm("weight_buy", value)}
                  helper="Otomatis dari total berat pada baris pembelian."
                  readOnly
                />
                <MetricField
                  label="Berat masuk"
                  actual={detail.actuals.weight_received}
                  value={form.weight_received}
                  onChange={(value) => patchForm("weight_received", value)}
                  helper="Otomatis dari berat diterima valid pada pembelian. Jika belum ada, sistem memakai berat beli."
                  readOnly
                />
                <MetricField
                  label="Berat akhir"
                  actual={detail.actuals.weight_final}
                  value={form.weight_final}
                  onChange={(value) => patchForm("weight_final", value)}
                  helper="Otomatis dihitung dari berat masuk setelah susut/tambah aktual."
                  readOnly
                />
                <MetricField label="Berat naik %" actual={detail.summary.berat_naik_percent} value={form.weight_gain_percent} onChange={(value) => patchForm("weight_gain_percent", value)} readOnly />
                <MetricField label="Susut / tambah" actual={detail.summary.susut_tambah} value={form.shrinkage_delta} onChange={(value) => patchForm("shrinkage_delta", value)} readOnly />
                <MetricField label="Kadar beli %" actual={detail.actuals.moisture_buy_percent} value={form.moisture_buy_percent} onChange={(value) => patchForm("moisture_buy_percent", value)} readOnly />
                <MetricField label="Kadar masuk %" actual={detail.actuals.moisture_received_percent} value={form.moisture_received_percent} onChange={(value) => patchForm("moisture_received_percent", value)} readOnly />
                <MetricField label="Kadar akhir %" actual={detail.actuals.moisture_final_percent} value={form.moisture_final_percent} onChange={(value) => patchForm("moisture_final_percent", value)} readOnly />
                <MetricField label="Brg atas rata2 %" actual={detail.actuals.above_average_ratio_percent} value={form.above_average_ratio_percent} onChange={(value) => patchForm("above_average_ratio_percent", value)} readOnly />
                <MetricField label="MK %" actual={detail.summary.mk_percent} value={form.mk_percent} onChange={(value) => patchForm("mk_percent", value)} readOnly />
                <MetricField label="Non-MK %" actual={detail.summary.non_mk_percent} value={form.non_mk_percent} onChange={(value) => patchForm("non_mk_percent", value)} readOnly />
                <MetricField label="Harga rata2" actual={detail.summary.harga_rata2} value={form.average_price} onChange={(value) => patchForm("average_price", value)} readOnly />
                <MetricField label="Harga MK A/R" actual={detail.actuals.market_reference_price} value={form.market_reference_price} onChange={(value) => patchForm("market_reference_price", value)} readOnly />
                <MetricField label="Modal beli" actual={detail.summary.modal_beli} value={form.modal_beli} onChange={(value) => patchForm("modal_beli", value)} readOnly />
                <MetricField label="Modal masuk" actual={detail.summary.modal_masuk} value={form.modal_masuk} onChange={(value) => patchForm("modal_masuk", value)} readOnly />
                <MetricField label="Modal jual" actual={detail.summary.modal_jual} value={form.modal_jual} onChange={(value) => patchForm("modal_jual", value)} readOnly />
                <MetricField label="Modal barang" actual={detail.summary.modal_barang} value={form.modal_barang} onChange={(value) => patchForm("modal_barang", value)} readOnly />
                <MetricField label="Total modal beli" actual={detail.summary.total_modal_beli} value={form.total_modal_beli} onChange={(value) => patchForm("total_modal_beli", value)} readOnly />
                <MetricField
                  label="Total modal MAL"
                  actual={detail.summary.total_modal_mal}
                  value={form.total_modal_mal}
                  onChange={(value) => patchForm("total_modal_mal", value)}
                  helper="Otomatis dari total baris pembelian berdasarkan harga MAL per item."
                  readOnly
                />
                <MetricField label="Laba/rugi agen" actual={detail.summary.laba_rugi_agen} value={form.agent_profit_share_total} onChange={(value) => patchForm("agent_profit_share_total", value)} readOnly />
              </div>

              <label className="mt-5 block">
                <span className="ops-label">{dict.purchaseAnalysisModule.analysisNotes}</span>
                <textarea
                  rows={3}
                  value={form.notes}
                  onChange={(event) => patchForm("notes", event.target.value)}
                  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">
                  <div>
                    <p className="ops-title">{dict.purchaseAnalysisModule.operationalCostTitle}</p>
                    <p className="ops-copy">{dict.purchaseAnalysisModule.operationalCostCopy}</p>
                  </div>
                  <button type="button" onClick={addCostEntry} className="ops-btn-secondary">
                    {dict.purchaseAnalysisModule.addCost}
                  </button>
                </div>
                <div className="mt-4 space-y-3">
                  {form.cost_entries.map((entry, index) => (
                    <div key={`${entry.id ?? "new"}-${index}`} className="grid gap-3 rounded-lg border border-line/70 bg-white p-3 md:grid-cols-[1fr_1.2fr_0.8fr_auto]">
                      <input
                        value={entry.cost_type}
                        onChange={(event) => updateCostEntry(index, { cost_type: event.target.value })}
                        placeholder={dict.purchaseAnalysisModule.costType}
                        className="ops-input"
                      />
                      <input
                        value={entry.description}
                        onChange={(event) => updateCostEntry(index, { description: event.target.value })}
                        placeholder={dict.purchaseAnalysisModule.costDescription}
                        className="ops-input"
                      />
                      <input
                        value={entry.amount}
                        onChange={(event) => updateCostEntry(index, { amount: event.target.value })}
                        placeholder={dict.purchaseAnalysisModule.amount}
                        inputMode="decimal"
                        className="ops-input"
                      />
                      <button type="button" onClick={() => removeCostEntry(index)} className="ops-btn-secondary">
                        {dict.purchaseAnalysisModule.delete}
                      </button>
                    </div>
                  ))}
                </div>
              </div>

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

            <div className="ops-card overflow-hidden">
              <div className="ops-section-head">
                <div>
                  <p className="ops-title">Sheet hasil analisis</p>
                  <p className="ops-copy">Ringkasan ini meniru struktur kerja manual agar transisi ke sistem tetap natural.</p>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="min-w-full text-sm">
                  <tbody className="divide-y divide-line/70">
                    {summaryRows.map(([label, value]) => (
                      <tr key={label} className="bg-white">
                        <td className="px-6 py-3 font-semibold text-ink">{label}</td>
                        <td className="px-6 py-3 text-right text-slate-700">{value}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        )}
      </div>
    </section>
  );
}

function MetricField({
  label,
  actual,
  value,
  onChange,
  helper,
  readOnly = false
}: {
  label: string;
  actual: number | null;
  value: string;
  onChange: (value: string) => void;
  helper?: string;
  readOnly?: boolean;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <input
        value={value}
        onChange={(event) => onChange(event.target.value)}
        inputMode="decimal"
        readOnly={readOnly}
        className={`ops-input ${readOnly ? "bg-slate-50 text-slate-600" : ""}`}
      />
      {helper ? <span className="mt-2 block text-xs text-slate-500">{helper}</span> : null}
      <span className="mt-2 block text-xs text-slate-500">
        Basis sistem: {actual === null ? "-" : actual.toLocaleString("id-ID")}
      </span>
    </label>
  );
}
