"use client";

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

import { useLocale } from "@/components/providers/locale-provider";
import { EmptyState, StatCard } from "@/components/shared/ops-primitives";
import type { Buyer } from "@/features/buyers/types/buyer";
import { formatCurrencyAmount, formatDecimal } from "@/lib/formatters";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type { CourierRecord, CurrencyRecord } from "@/types/master-data";
import type {
  RegularSaleCandidateLot,
  RegularSaleDetail,
  RegularSaleListItem
} from "@/types/regular-sale";

type CreateLineForm = {
  lot_id: string;
  qty_planned: string;
  selling_price_planned: string;
  notes: string;
};

type CreateForm = {
  sale_date: string;
  buyer_id: string;
  buyer_currency_code: string;
  company_currency_code: string;
  exchange_rate: string;
  courier_id: string;
  shipping_cost_buyer: string;
  notes: string;
  shipping_receipt_file: File | null;
  lines: CreateLineForm[];
};

type CloseLineForm = {
  qty_actual_sold: string;
  qty_returned: string;
  selling_price_actual: string;
};

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

const emptyCreateForm = (companyCurrencyCode = "IDR"): CreateForm => ({
  sale_date: new Date().toISOString().slice(0, 10),
  buyer_id: "",
  buyer_currency_code: companyCurrencyCode,
  company_currency_code: companyCurrencyCode,
  exchange_rate: "",
  courier_id: "",
  shipping_cost_buyer: "0",
  notes: "",
  shipping_receipt_file: null,
  lines: [newCreateLine()]
});

function statusChip(status: string) {
  if (status === "CLOSED") return "ops-chip-active";
  return "ops-chip-warning";
}

type SalesRegularClientProps = {
  defaultCurrencyCode: string;
};

export function SalesRegularClient({ defaultCurrencyCode }: SalesRegularClientProps) {
  const { locale, dict } = useLocale();
  const searchParams = useSearchParams();
  const requestedId = searchParams.get("id");
  const [items, setItems] = useState<RegularSaleListItem[]>([]);
  const [buyers, setBuyers] = useState<Buyer[]>([]);
  const [couriers, setCouriers] = useState<CourierRecord[]>([]);
  const [currencies, setCurrencies] = useState<CurrencyRecord[]>([]);
  const [lots, setLots] = useState<RegularSaleCandidateLot[]>([]);
  const [form, setForm] = useState<CreateForm>(emptyCreateForm(defaultCurrencyCode));
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<RegularSaleDetail | null>(null);
  const [closeDate, setCloseDate] = useState(new Date().toISOString().slice(0, 10));
  const [closeLines, setCloseLines] = useState<Record<string, CloseLineForm>>({});
  const [closeReceiptFile, setCloseReceiptFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(true);
  const [detailLoading, setDetailLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [closing, setClosing] = useState(false);
  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/sales-regular", { cache: "no-store" }),
        fetch("/api/v1/sales-regular/bootstrap", { cache: "no-store" })
      ]);

      const listPayload = (await listRes.json()) as { data: RegularSaleListItem[] } | ApiErrorResponse;
      const bootstrapPayload = (await bootstrapRes.json()) as
        | {
            data: {
              default_company_currency_code: string;
              buyers: Buyer[];
              couriers: CourierRecord[];
              currencies: CurrencyRecord[];
              lots: RegularSaleCandidateLot[];
            };
          }
        | ApiErrorResponse;

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

      setItems(listPayload.data);
      setBuyers(bootstrapPayload.data.buyers);
      setCouriers(bootstrapPayload.data.couriers);
      setCurrencies(bootstrapPayload.data.currencies);
      setLots(bootstrapPayload.data.lots);
      setForm((current) => {
        if (current.company_currency_code) return current;
        return emptyCreateForm(bootstrapPayload.data.default_company_currency_code);
      });

      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 penjualan reguler.");
    } 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/sales-regular/${id}`, { cache: "no-store" });
      const payload = (await response.json()) as DetailResponse<RegularSaleDetail> | ApiErrorResponse;

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

      setSelectedId(id);
      setDetail(payload.data);
      setCloseDate(new Date().toISOString().slice(0, 10));
      setCloseReceiptFile(null);
      setCloseLines(
        payload.data.lines.reduce<Record<string, CloseLineForm>>((acc, line) => {
          acc[line.id] = {
            qty_actual_sold: String(line.qty_planned),
            qty_returned: "0",
            selling_price_actual: String(line.selling_price_planned)
          };
          return acc;
        }, {})
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat detail penjualan reguler.");
    } 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 saveSale() {
    setSaving(true);
    setError(null);
    try {
      const payload = {
        sale_date: form.sale_date,
        buyer_id: form.buyer_id,
        buyer_currency_code: form.buyer_currency_code,
        company_currency_code: form.company_currency_code,
        exchange_rate:
          form.buyer_currency_code === form.company_currency_code
            ? null
            : Number(form.exchange_rate || 0),
        courier_id: form.courier_id || null,
        shipping_cost_buyer: Number(form.shipping_cost_buyer || 0),
        notes: form.notes || null,
        lines: form.lines.map((line) => ({
          lot_id: line.lot_id,
          qty_planned: Number(line.qty_planned),
          selling_price_planned: Number(line.selling_price_planned),
          notes: line.notes || null
        }))
      };

      const hasFile = Boolean(form.shipping_receipt_file);
      const response = await fetch("/api/v1/sales-regular", {
        method: "POST",
        body: hasFile
          ? (() => {
              const formData = new FormData();
              formData.set("payload", JSON.stringify(payload));
              formData.set("shipping_receipt", form.shipping_receipt_file!);
              return formData;
            })()
          : JSON.stringify(payload),
        headers: hasFile ? undefined : { "Content-Type": "application/json" }
      });

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

      setForm(emptyCreateForm(form.company_currency_code || defaultCurrencyCode));
      await loadAll(payloadRes.data.id);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menyimpan penjualan reguler.");
    } finally {
      setSaving(false);
    }
  }

  function patchCloseLine(lineId: string, patch: Partial<CloseLineForm>) {
    setCloseLines((current) => ({
      ...current,
      [lineId]: { ...(current[lineId] ?? { qty_actual_sold: "", qty_returned: "", selling_price_actual: "" }), ...patch }
    }));
  }

  async function closeSale() {
    if (!detail) return;

    setClosing(true);
    setError(null);
    try {
      const payload = {
        close_date: closeDate,
        lines: detail.lines.map((line) => ({
          line_id: line.id,
          qty_actual_sold: Number(closeLines[line.id]?.qty_actual_sold || 0),
          qty_returned: Number(closeLines[line.id]?.qty_returned || 0),
          selling_price_actual: Number(closeLines[line.id]?.selling_price_actual || 0)
        }))
      };

      const hasFile = Boolean(closeReceiptFile);
      const response = await fetch(`/api/v1/sales-regular/${detail.id}/close`, {
        method: "POST",
        body: hasFile
          ? (() => {
              const formData = new FormData();
              formData.set("payload", JSON.stringify(payload));
              formData.set("shipping_receipt", closeReceiptFile!);
              return formData;
            })()
          : JSON.stringify(payload),
        headers: hasFile ? undefined : { "Content-Type": "application/json" }
      });

      const payloadRes = (await response.json()) as DetailResponse<RegularSaleDetail> | ApiErrorResponse;
      if (!response.ok) {
        const validationMessage =
          "errors" in payloadRes && payloadRes.errors
            ? Object.values(payloadRes.errors)[0]?.[0]
            : null;
        throw new Error(validationMessage ?? ("message" in payloadRes ? payloadRes.message : "Gagal menutup penjualan reguler."));
      }
      if (!("data" in payloadRes)) {
        throw new Error("Gagal menutup penjualan reguler.");
      }

      await loadAll(payloadRes.data.id);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menutup penjualan reguler.");
    } finally {
      setClosing(false);
    }
  }

  const selectedBuyer = buyers.find((buyer) => buyer.id === form.buyer_id) ?? null;
  const selectedCourier = couriers.find((courier) => courier.id === form.courier_id) ?? null;
  const selectedLotIds = form.lines.map((line) => line.lot_id).filter(Boolean);
  const createRate =
    form.buyer_currency_code === form.company_currency_code ? 1 : Number(form.exchange_rate || 0);
  const shippingEquivalent = Number(form.shipping_cost_buyer || 0) * createRate;

  const createSummary = useMemo(() => {
    return form.lines.reduce(
      (acc, line) => {
        const selectedLot = lots.find((lot) => lot.lot_id === line.lot_id);
        const qty = Number(line.qty_planned || 0);
        const sellingPrice = Number(line.selling_price_planned || 0);
        const nominalBuyer = qty * sellingPrice;
        const nominalSeller = nominalBuyer * createRate;
        const malUnitPrice = selectedLot?.mal_unit_price ?? 0;
        const shareAgent = selectedLot?.agent_share_percent ?? 0;
        const commission = ((sellingPrice * createRate - malUnitPrice) * qty * shareAgent) / 100;

        acc.total_nominal_buyer += nominalBuyer;
        acc.total_nominal_company += nominalSeller;
        acc.total_agent_commission += selectedLot?.agent_share_percent ? commission : 0;
        return acc;
      },
      {
        total_nominal_buyer: 0,
        total_nominal_company: 0,
        total_agent_commission: 0
      }
    );
  }, [createRate, form.lines, lots]);

  const closeSummary = useMemo(() => {
    if (!detail) return { totalNominalBuyer: 0, totalNominalCompany: 0, totalAgentCommission: 0 };
    const rate = detail.exchange_rate ?? 1;

    return detail.lines.reduce(
      (acc, line) => {
        const closeLine = closeLines[line.id];
        const qtyActualSold = Number(closeLine?.qty_actual_sold || 0);
        const sellingPriceActual = Number(closeLine?.selling_price_actual || 0);
        const nominalBuyer = qtyActualSold * sellingPriceActual;
        const nominalSeller = nominalBuyer * rate;
        const commission =
          line.agent_share_percent && line.mal_unit_price_snapshot !== null
            ? ((sellingPriceActual * rate - line.mal_unit_price_snapshot) *
                qtyActualSold *
                line.agent_share_percent) /
              100
            : 0;

        acc.totalNominalBuyer += nominalBuyer;
        acc.totalNominalCompany += nominalSeller;
        acc.totalAgentCommission += commission;
        return acc;
      },
      {
        totalNominalBuyer: 0,
        totalNominalCompany: 0,
        totalAgentCommission: 0
      }
    );
  }, [closeLines, detail]);

  return (
    <section className="space-y-6">
      {detail ? (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <StatCard label="Penjualan" value={detail.sale_no} hint={`${detail.buyer.name} · ${detail.status}`} />
          <StatCard
            label={dict.regularSales.totalNominal}
            value={formatCurrencyAmount(detail.total_nominal_buyer, locale, detail.buyer_currency_code, 0)}
            hint={
              detail.buyer_currency_code === detail.company_currency_code
                ? detail.company_currency_code
                : `${formatCurrencyAmount(detail.total_nominal_company, locale, detail.company_currency_code, 0)} ekuivalen`
            }
          />
          <StatCard
            label={dict.regularSales.totalAgentCommission}
            value={formatCurrencyAmount(detail.total_agent_commission, locale, detail.company_currency_code, 0)}
            hint="Dihitung dari spread jual aktual vs harga MAL"
          />
          <StatCard
            label={dict.regularSales.shippingCost}
            value={formatCurrencyAmount(detail.shipping_cost_buyer, locale, detail.buyer_currency_code, 0)}
            hint={
              detail.buyer_currency_code === detail.company_currency_code
                ? detail.company_currency_code
                : `${formatCurrencyAmount(detail.shipping_cost_company, locale, detail.company_currency_code, 0)} ekuivalen`
            }
          />
        </div>
      ) : null}

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

          <div className="mt-6 grid gap-4 md:grid-cols-2">
            <Field label={dict.regularSales.code} value={dict.regularSales.codeAuto} readOnly />
            <Field label={dict.regularSales.saleDate} value={form.sale_date} onChange={(value) => patchForm("sale_date", value)} type="date" />
            <SelectField
              label={dict.regularSales.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.regularSales.chooseBuyer}
            />
            <SelectField
              label={dict.regularSales.buyerCurrency}
              value={form.buyer_currency_code}
              onChange={(value) => patchForm("buyer_currency_code", value)}
              options={currencies.map((currency) => ({ value: currency.code, label: `${currency.code} - ${currency.name}` }))}
              placeholder={dict.regularSales.chooseBuyerCurrency}
            />
            <SelectField
              label={dict.regularSales.companyCurrency}
              value={form.company_currency_code}
              onChange={(value) => patchForm("company_currency_code", value)}
              options={currencies.map((currency) => ({ value: currency.code, label: `${currency.code} - ${currency.name}` }))}
              placeholder={dict.regularSales.chooseCompanyCurrency}
            />
            <SelectField
              label={locale === "id" ? "Jasa Pengiriman" : "Courier"}
              value={form.courier_id}
              onChange={(value) => patchForm("courier_id", value)}
              options={couriers.map((courier) => ({ value: courier.id, label: `${courier.code} - ${courier.name}` }))}
              placeholder={locale === "id" ? "Pilih jasa pengiriman" : "Choose courier"}
            />
            {form.buyer_currency_code !== form.company_currency_code ? (
              <Field label={dict.regularSales.buyerRate} value={form.exchange_rate} onChange={(value) => patchForm("exchange_rate", value)} placeholder="0.000000" />
            ) : (
              <InfoCard label={dict.regularSales.buyerRate} value="1.000000" />
            )}
            <Field label={`${dict.regularSales.shippingCost} (${form.buyer_currency_code || "-"})`} value={form.shipping_cost_buyer} onChange={(value) => patchForm("shipping_cost_buyer", value)} />
          </div>

          {(selectedBuyer || selectedCourier || form.buyer_currency_code !== form.company_currency_code) ? (
            <div className="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
              <InfoCard label={dict.regularSales.buyer} value={selectedBuyer ? `${selectedBuyer.code} · ${selectedBuyer.name}` : "-"} />
              <InfoCard label={locale === "id" ? "Jasa Pengiriman" : "Courier"} value={selectedCourier ? `${selectedCourier.code} · ${selectedCourier.name}` : "-"} />
              {form.buyer_currency_code !== form.company_currency_code ? (
                <InfoCard
                  label={dict.regularSales.shippingEquivalent}
                  value={formatCurrencyAmount(shippingEquivalent, locale, form.company_currency_code || defaultCurrencyCode, 0)}
                />
              ) : null}
            </div>
          ) : null}

          <label className="mt-5 block">
            <span className="ops-label">{dict.regularSales.shippingReceipt}</span>
            <input
              type="file"
              accept=".jpg,.jpeg,.png,.pdf"
              onChange={(event) => patchForm("shipping_receipt_file", event.target.files?.[0] ?? null)}
              className="ops-input pt-2"
            />
          </label>

          <label className="mt-5 block">
            <span className="ops-label">{dict.regularSales.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.regularSales.soldItems}</p>
                <p className="ops-copy">{dict.regularSales.soldItemsCopy}</p>
              </div>
              <button type="button" onClick={addLine} className="ops-btn-secondary">
                {dict.regularSales.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 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-3.5">
                    <div className="grid gap-3 lg:grid-cols-[minmax(0,1.45fr)_minmax(0,0.74fr)_minmax(0,0.92fr)_64px]">
                      <SelectField
                        label={locale === "id" ? "Lot" : "Lot"}
                        value={line.lot_id}
                        onChange={(value) => updateLine(index, { lot_id: value, qty_planned: "", selling_price_planned: "" })}
                        options={allowedLots.map((lot) => ({
                          value: lot.lot_id,
                          label: `${lot.lot_code} · ${lot.grade}`
                        }))}
                        placeholder={locale === "id" ? "Pilih lot aktif" : "Choose active lot"}
                        compact
                      />
                      <Field label={dict.regularSales.sellWeight} value={line.qty_planned} onChange={(value) => updateLine(index, { qty_planned: value })} placeholder={selectedLot ? `Max ${selectedLot.available_qty}` : "0.000"} compact />
                      <Field label={`${dict.regularSales.sellingPrice} (${form.buyer_currency_code || defaultCurrencyCode})`} value={line.selling_price_planned} onChange={(value) => updateLine(index, { selling_price_planned: value })} compact />
                      <div className="flex items-end pt-[2.55rem]">
                        <button
                          type="button"
                          onClick={() => removeLine(index)}
                          className="inline-flex h-[52px] w-[52px] items-center justify-center rounded-xl border border-line/70 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-ember"
                          aria-label={locale === "id" ? "Hapus baris" : "Remove row"}
                          title={locale === "id" ? "Hapus baris" : "Remove row"}
                        >
                          <Trash2 className="h-5 w-5" />
                        </button>
                      </div>
                    </div>

                    {selectedLot ? (
                      <div className="mt-3.5 grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                        <CompactInfoCard label={locale === "id" ? "Grade" : "Grade"} value={selectedLot.grade} />
                        <CompactInfoCard label={locale === "id" ? "Kode lot" : "Lot code"} value={selectedLot.lot_code} />
                        <CompactInfoCard label={dict.regularSales.currentWeight} value={`${formatDecimal(selectedLot.available_qty, locale)} ${selectedLot.unit_code}`} />
                        <CompactInfoCard
                          label={`${dict.regularSales.malPrice} (${form.company_currency_code || defaultCurrencyCode})`}
                          value={
                            selectedLot.mal_unit_price === null
                              ? "-"
                              : formatCurrencyAmount(selectedLot.mal_unit_price, locale, form.company_currency_code || defaultCurrencyCode, 0)
                          }
                        />
                        <CompactInfoCard
                          label={dict.regularSales.agentShare}
                          value={
                            selectedLot.agent_share_percent
                              ? `${selectedLot.agent_name ?? (locale === "id" ? "Agen" : "Agent")} · ${formatDecimal(selectedLot.agent_share_percent, locale, 2)}%`
                              : "-"
                          }
                        />
                      </div>
                    ) : null}

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

          <div className="mt-5 grid gap-4 md:grid-cols-3">
            <InfoCard
              label={dict.regularSales.totalNominal}
              value={formatCurrencyAmount(createSummary.total_nominal_buyer, locale, form.buyer_currency_code || defaultCurrencyCode, 0)}
            />
            <InfoCard
              label={dict.regularSales.totalEquivalent}
              value={formatCurrencyAmount(createSummary.total_nominal_company, locale, form.company_currency_code || defaultCurrencyCode, 0)}
            />
            <InfoCard
              label={dict.regularSales.totalAgentCommission}
              value={formatCurrencyAmount(createSummary.total_agent_commission, locale, form.company_currency_code || defaultCurrencyCode, 0)}
            />
          </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 saveSale()} className="ops-btn-primary" disabled={saving}>
              {saving ? dict.common.processing : dict.regularSales.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.regularSales.listTitle}</p>
                <p className="ops-copy">{dict.regularSales.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.regularSales.noData} copy={dict.regularSales.noDataCopy} />
            ) : (
              <div className="overflow-x-auto">
                <table className="ops-table">
                  <thead>
                    <tr>
                      <th>{dict.regularSales.code}</th>
                      <th>{dict.regularSales.buyer}</th>
                      <th>{locale === "id" ? "Status" : "Status"}</th>
                      <th>{locale === "id" ? "Total" : "Total"}</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.sale_no}</td>
                        <td>
                          <div className="font-medium text-ink">{item.buyer.name}</div>
                          <div className="text-xs text-slate-500">{item.buyer_currency_code}</div>
                        </td>
                        <td>
                          <span className={statusChip(item.status)}>{item.status}</span>
                        </td>
                        <td>{formatCurrencyAmount(item.total_nominal_buyer, locale, item.buyer_currency_code, 0)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

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

              <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <InfoCard label={dict.regularSales.buyer} value={`${detail.buyer.code} · ${detail.buyer.name}`} />
                <InfoCard label={locale === "id" ? "Jasa Pengiriman" : "Courier"} value={detail.courier ? `${detail.courier.code} · ${detail.courier.name}` : "-"} />
                <InfoCard label={dict.regularSales.buyerCompanyCurrency} value={`${detail.buyer_currency_code} / ${detail.company_currency_code}`} />
                <InfoCard label={dict.regularSales.rate} value={detail.exchange_rate === null ? "1.000000" : formatDecimal(detail.exchange_rate, locale, 6)} />
              </div>

              {detail.shipping_receipt_file_url ? (
                <div className="mt-4 rounded border border-line/70 bg-slate-50/70 px-4 py-3 text-sm text-slate-600">
                  {locale === "id" ? "Resi pengiriman" : "Shipping receipt"}:
                  {" "}
                  <a href={detail.shipping_receipt_file_url} target="_blank" rel="noreferrer" className="font-medium text-azure underline">
                    {dict.regularSales.viewFile}
                  </a>
                </div>
              ) : null}

              <div className="mt-6 space-y-5">
                {detail.lines.map((line) => {
                  const closeLine = closeLines[line.id] ?? {
                    qty_actual_sold: String(line.qty_planned),
                    qty_returned: "0",
                    selling_price_actual: String(line.selling_price_planned)
                  };
                  const qtyActualSold = Number(closeLine.qty_actual_sold || 0);
                  const qtyReturned = Number(closeLine.qty_returned || 0);
                  const shrinkage = Math.max(0, Number((line.qty_planned - qtyActualSold - qtyReturned).toFixed(3)));

                  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_planned, locale)} {line.unit_code}
                          </div>
                        </div>
                        <div className="text-right text-xs text-slate-500">
                          {locale === "id" ? "Gudang" : "Warehouse"} {line.warehouse}
                          {line.location ? ` · ${line.location}` : ""}
                        </div>
                      </div>

                      <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                        <InfoCard label={dict.regularSales.currentSellWeight} value={`${formatDecimal(line.available_qty_snapshot, locale)} ${line.unit_code}`} />
                        <InfoCard label={dict.regularSales.outgoingWeight} value={`${formatDecimal(line.qty_planned, locale)} ${line.unit_code}`} />
                        <InfoCard
                          label={`${dict.regularSales.malPrice} (${detail.company_currency_code})`}
                          value={
                            line.mal_unit_price_snapshot === null
                              ? "-"
                              : formatCurrencyAmount(line.mal_unit_price_snapshot, locale, detail.company_currency_code, 0)
                          }
                        />
                        <InfoCard
                          label={`${dict.regularSales.plannedSellingPrice} (${detail.buyer_currency_code})`}
                          value={formatCurrencyAmount(line.selling_price_planned, locale, detail.buyer_currency_code, 0)}
                        />
                        <InfoCard label={dict.regularSales.agentShare} value={line.agent_share_percent ? `${line.agent_name ?? (locale === "id" ? "Agen" : "Agent")} · ${formatDecimal(line.agent_share_percent, locale, 2)}%` : "-"} />
                      </div>

                      {detail.status === "CLOSED" ? (
                        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
                          <InfoCard label={locale === "id" ? "Berat jual aktual" : "Actual sold weight"} value={formatDecimal(line.qty_actual_sold ?? 0, locale)} />
                          <InfoCard label={dict.regularSales.returnWeight} value={formatDecimal(line.qty_returned ?? 0, locale)} />
                          <InfoCard label={dict.regularSales.shrinkageWeight} value={formatDecimal(line.qty_shrinkage ?? 0, locale)} />
                          <InfoCard
                            label={`${dict.regularSales.actualSellingPrice} (${detail.buyer_currency_code})`}
                            value={formatCurrencyAmount(line.selling_price_actual ?? 0, locale, detail.buyer_currency_code, 0)}
                          />
                          <InfoCard label={dict.regularSales.currentWeight} value={`${formatDecimal(line.current_available_qty, locale)} ${line.unit_code}`} />
                        </div>
                      ) : (
                        <div className="mt-4">
                          <div className="grid gap-4 md:grid-cols-3">
                            <Field label={locale === "id" ? "Berat jual aktual" : "Actual sold weight"} value={closeLine.qty_actual_sold} onChange={(value) => patchCloseLine(line.id, { qty_actual_sold: value })} />
                            <Field label={dict.regularSales.returnWeight} value={closeLine.qty_returned} onChange={(value) => patchCloseLine(line.id, { qty_returned: value })} />
                            <Field label={`${dict.regularSales.actualSellingPrice} (${detail.buyer_currency_code})`} value={closeLine.selling_price_actual} onChange={(value) => patchCloseLine(line.id, { selling_price_actual: value })} />
                          </div>
                          <div className="mt-3 rounded border border-line/70 bg-white px-4 py-3 text-sm text-slate-600">
                            {dict.regularSales.autoShrinkageHint}
                            {" "}
                            <span className="font-semibold text-ink">{formatDecimal(shrinkage, locale)} {line.unit_code}</span>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {detail.status !== "CLOSED" ? (
                <>
                  <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    <Field label={dict.regularSales.closeDate} value={closeDate} onChange={setCloseDate} type="date" />
                    <label className="block md:col-span-2">
                      <span className="ops-label">{dict.regularSales.updateReceipt}</span>
                      <input
                        type="file"
                        accept=".jpg,.jpeg,.png,.pdf"
                        onChange={(event) => setCloseReceiptFile(event.target.files?.[0] ?? null)}
                        className="ops-input pt-2"
                      />
                    </label>
                    <InfoCard
                      label={dict.regularSales.shippingEquivalent}
                      value={formatCurrencyAmount(detail.shipping_cost_company, locale, detail.company_currency_code, 0)}
                    />
                  </div>

                  <div className="mt-5 grid gap-4 md:grid-cols-3">
                    <InfoCard label={dict.regularSales.totalNominal} value={formatCurrencyAmount(closeSummary.totalNominalBuyer, locale, detail.buyer_currency_code, 0)} />
                    <InfoCard label={dict.regularSales.totalEquivalent} value={formatCurrencyAmount(closeSummary.totalNominalCompany, locale, detail.company_currency_code, 0)} />
                    <InfoCard label={dict.regularSales.totalAgentCommission} value={formatCurrencyAmount(closeSummary.totalAgentCommission, locale, detail.company_currency_code, 0)} />
                  </div>

                  <div className="mt-6 flex justify-end">
                    <button type="button" onClick={() => void closeSale()} className="ops-btn-primary" disabled={closing}>
                      {closing ? dict.common.processing : dict.regularSales.closeAll}
                    </button>
                  </div>
                </>
              ) : null}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  placeholder,
  readOnly = false,
  compact = false
}: {
  label: string;
  value: string;
  onChange?: (value: string) => void;
  type?: string;
  placeholder?: string;
  readOnly?: boolean;
  compact?: boolean;
}) {
  return (
    <label className="block">
      <span className={compact ? "mb-2 block min-h-[2.5rem] text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500" : "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,
  compact = false
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Array<{ value: string; label: string }>;
  placeholder: string;
  compact?: boolean;
}) {
  return (
    <label className="block">
      <span className={compact ? "mb-2 block min-h-[2.5rem] text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500" : "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="min-h-[88px] 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 text-[11px] font-medium leading-5 text-ink break-words">{value}</p>
    </div>
  );
}
