"use client";

import { Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { EmptyState } from "@/components/shared/ops-primitives";
import { SearchableSelectField } from "@/components/shared/searchable-select-field";
import type { Buyer } from "@/features/buyers/types/buyer";
import { formatCurrencyAmount, formatDecimal } from "@/lib/formatters";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type { JitSaleDetail, JitSaleListItem } from "@/types/jit-sale";
import type {
  AgentRecord,
  CourierRecord,
  CurrencyRecord,
  GradeRecord,
  ProfitShareSchemeRecord
} from "@/types/master-data";

type CreateLineForm = {
  grade_id: string;
  qty_planned: string;
  mal_unit_price: string;
  selling_price_planned: string;
  agent_id: string;
  profit_share_scheme_id: 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 = {
  selling_price_actual: string;
};

const newCreateLine = (): CreateLineForm => ({
  grade_id: "",
  qty_planned: "",
  mal_unit_price: "",
  selling_price_planned: "",
  agent_id: "",
  profit_share_scheme_id: "",
  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) {
  return status === "CLOSED" ? "ops-chip-active" : "ops-chip-warning";
}

function SmallInfoCard({
  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>
  );
}

type SalesJitClientProps = {
  defaultCurrencyCode: string;
};

export function SalesJitClient({ defaultCurrencyCode }: SalesJitClientProps) {
  const { locale, dict } = useLocale();
  const [items, setItems] = useState<JitSaleListItem[]>([]);
  const [buyers, setBuyers] = useState<Buyer[]>([]);
  const [couriers, setCouriers] = useState<CourierRecord[]>([]);
  const [currencies, setCurrencies] = useState<CurrencyRecord[]>([]);
  const [grades, setGrades] = useState<GradeRecord[]>([]);
  const [agents, setAgents] = useState<AgentRecord[]>([]);
  const [profitShareSchemes, setProfitShareSchemes] = useState<ProfitShareSchemeRecord[]>([]);
  const [form, setForm] = useState<CreateForm>(emptyCreateForm(defaultCurrencyCode));
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<JitSaleDetail | 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-jit", { cache: "no-store" }),
        fetch("/api/v1/sales-jit/bootstrap", { cache: "no-store" })
      ]);

      const listPayload = (await listRes.json()) as { data: JitSaleListItem[] } | ApiErrorResponse;
      const bootstrapPayload = (await bootstrapRes.json()) as
        | {
            data: {
              default_company_currency_code: string;
              buyers: Buyer[];
              couriers: CourierRecord[];
              currencies: CurrencyRecord[];
              grades: GradeRecord[];
              agents: AgentRecord[];
              profit_share_schemes: ProfitShareSchemeRecord[];
            };
          }
        | ApiErrorResponse;

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

      setItems(listPayload.data);
      setBuyers(bootstrapPayload.data.buyers);
      setCouriers(bootstrapPayload.data.couriers);
      setCurrencies(bootstrapPayload.data.currencies);
      setGrades(bootstrapPayload.data.grades);
      setAgents(bootstrapPayload.data.agents);
      setProfitShareSchemes(bootstrapPayload.data.profit_share_schemes);
      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 just in time.");
    } finally {
      setLoading(false);
    }
  }

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

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

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

      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] = {
            selling_price_actual: String(line.selling_price_planned)
          };
          return acc;
        }, {})
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat detail penjualan just in time.");
    } 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)
    }));
  }

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

  function resetForm() {
    setForm(emptyCreateForm(form.company_currency_code || defaultCurrencyCode));
    setError(null);
  }

  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) => ({
          grade_id: line.grade_id,
          qty_planned: Number(line.qty_planned),
          mal_unit_price: Number(line.mal_unit_price),
          selling_price_planned: Number(line.selling_price_planned),
          agent_id: line.agent_id || null,
          profit_share_scheme_id: line.profit_share_scheme_id || null,
          notes: line.notes || null
        }))
      };

      const hasFile = Boolean(form.shipping_receipt_file);
      const response = await fetch("/api/v1/sales-jit", {
        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<JitSaleDetail> | 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 just in time.")
        );
      }
      if (!("data" in payloadRes)) {
        throw new Error("Gagal menyimpan penjualan just in time.");
      }

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

  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,
          selling_price_actual: Number(closeLines[line.id]?.selling_price_actual || 0)
        }))
      };

      const hasFile = Boolean(closeReceiptFile);
      const response = await fetch(`/api/v1/sales-jit/${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<JitSaleDetail> | 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 just in time.")
        );
      }
      if (!("data" in payloadRes)) {
        throw new Error("Gagal menutup penjualan just in time.");
      }

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

  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 qty = Number(line.qty_planned || 0);
        const sellingPrice = Number(line.selling_price_planned || 0);
        const malPrice = Number(line.mal_unit_price || 0);
        const scheme = profitShareSchemes.find((item) => item.id === line.profit_share_scheme_id) ?? null;
        const nominalBuyer = qty * sellingPrice;
        const nominalCompany = nominalBuyer * createRate;
        const commission =
          ((sellingPrice * createRate - malPrice) * qty * (scheme?.share_agent ?? 0)) / 100;

        acc.total_nominal_buyer += nominalBuyer;
        acc.total_nominal_company += nominalCompany;
        acc.total_agent_commission += line.agent_id ? commission : 0;
        return acc;
      },
      {
        total_nominal_buyer: 0,
        total_nominal_company: 0,
        total_agent_commission: 0
      }
    );
  }, [createRate, form.lines, profitShareSchemes]);

  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 sellingPriceActual = Number(closeLine?.selling_price_actual || 0);
        const qty = line.qty_planned;
        const nominalBuyer = qty * sellingPriceActual;
        const nominalCompany = nominalBuyer * rate;
        const commission =
          ((sellingPriceActual * rate - line.mal_unit_price) *
            qty *
            (line.agent_share_percent ?? 0)) /
          100;

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

  if (loading) {
    return <div className="ops-card p-6 text-sm text-slate-500">Memuat penjualan just in time...</div>;
  }

  return (
    <div className="space-y-6">
      {error ? (
        <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
          {error}
        </div>
      ) : null}

      <section 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.jitSales.overline}</p>
              <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">{dict.jitSales.title}</h2>
              <p className="mt-3 max-w-3xl text-[13px] leading-6 text-slate-500">{dict.jitSales.helper}</p>
            </div>
            <button
              type="button"
              className="ops-btn-secondary"
              onClick={resetForm}
            >
              {dict.common.formReset}
            </button>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="ops-label">{dict.jitSales.code}</span>
              <input type="text" className="ops-input bg-slate-50" value={dict.jitSales.codeAuto} readOnly />
            </label>

            <label className="block">
              <span className="ops-label">Tanggal penjualan</span>
              <input
                type="date"
                className="ops-input"
                value={form.sale_date}
                onChange={(event) => patchForm("sale_date", event.target.value)}
              />
            </label>

            <label className="block">
              <span className="ops-label">{dict.jitSales.buyer}</span>
              <select
                className="ops-input"
                value={form.buyer_id}
                onChange={(event) => patchForm("buyer_id", event.target.value)}
              >
                <option value="">{dict.jitSales.chooseBuyer}</option>
                {buyers.map((buyer) => (
                  <option key={buyer.id} value={buyer.id}>
                    {buyer.code} · {buyer.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block">
              <span className="ops-label">{dict.jitSales.buyerCurrency}</span>
              <select
                className="ops-input"
                value={form.buyer_currency_code}
                onChange={(event) => patchForm("buyer_currency_code", event.target.value)}
              >
                {currencies.map((currency) => (
                  <option key={currency.id} value={currency.code}>
                    {currency.code} - {currency.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block">
              <span className="ops-label">{dict.jitSales.companyCurrency}</span>
              <select
                className="ops-input"
                value={form.company_currency_code}
                onChange={(event) => patchForm("company_currency_code", event.target.value)}
              >
                {currencies.map((currency) => (
                  <option key={currency.id} value={currency.code}>
                    {currency.code} - {currency.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block">
              <span className="ops-label">{dict.jitSales.courier}</span>
              <select
                className="ops-input"
                value={form.courier_id}
                onChange={(event) => patchForm("courier_id", event.target.value)}
              >
                <option value="">{dict.jitSales.chooseCourier}</option>
                {couriers.map((courier) => (
                  <option key={courier.id} value={courier.id}>
                    {courier.code} · {courier.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block">
              <span className="ops-label">{dict.jitSales.shippingCost} ({form.buyer_currency_code})</span>
              <input
                type="number"
                min="0"
                step="0.01"
                className="ops-input"
                value={form.shipping_cost_buyer}
                onChange={(event) => patchForm("shipping_cost_buyer", event.target.value)}
              />
            </label>

            {form.buyer_currency_code !== form.company_currency_code ? (
              <div className="rounded-2xl border border-line bg-slate-50/60 p-4">
                <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
                  {dict.jitSales.buyerRate}
                </p>
                <input
                  type="number"
                  min="0"
                  step="0.0001"
                  className="ops-input mt-3"
                  value={form.exchange_rate}
                  onChange={(event) => patchForm("exchange_rate", event.target.value)}
                  placeholder="0"
                />
              </div>
            ) : null}

            <label className="block md:col-span-2">
              <span className="ops-label">{dict.jitSales.uploadReceipt}</span>
              <input
                type="file"
                accept=".jpg,.jpeg,.png,.pdf"
                className="ops-input pt-3"
                onChange={(event) => patchForm("shipping_receipt_file", event.target.files?.[0] ?? null)}
              />
            </label>
          </div>

          {form.buyer_currency_code !== form.company_currency_code ? (
            <div className="mt-4 rounded-2xl border border-line bg-slate-50 px-4 py-3 text-sm text-slate-600">
              Ekivalen biaya kirim perusahaan:{" "}
              <span className="font-semibold text-ink">
                {formatCurrencyAmount(shippingEquivalent, locale, form.company_currency_code)}
              </span>
            </div>
          ) : null}

          <label className="mt-4 block">
            <span className="ops-label">{dict.jitSales.headerNotes}</span>
            <textarea
              className="ops-input min-h-[110px]"
              value={form.notes}
              onChange={(event) => patchForm("notes", event.target.value)}
              placeholder={locale === "id" ? "Opsional" : "Optional"}
            />
          </label>

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

            <div className="mt-4 space-y-4">
              {form.lines.map((line, index) => {
                const selectedGrade = grades.find((grade) => grade.id === line.grade_id) ?? null;
                const selectedAgent = agents.find((agent) => agent.id === line.agent_id) ?? null;
                const selectedScheme =
                  profitShareSchemes.find((scheme) => scheme.id === line.profit_share_scheme_id) ?? null;
                const qty = Number(line.qty_planned || 0);
                const malPrice = Number(line.mal_unit_price || 0);
                const sellingPrice = Number(line.selling_price_planned || 0);
                const previewCommission =
                  ((sellingPrice * createRate - malPrice) * qty * (selectedScheme?.share_agent ?? 0)) / 100;

                return (
                  <div key={`jit-line-${index}`} className="relative rounded-lg border border-line/70 bg-white p-4">
                    {index !== 0 ? (
                      <button
                        type="button"
                        onClick={() => removeLine(index)}
                        className="absolute right-4 top-4 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"}
                      >
                        <Trash2 className="h-5 w-5" />
                      </button>
                    ) : null}

                    <div className="grid gap-4 md:grid-cols-3">
                      <SearchableSelectField
                        label={dict.jitSales.grade}
                        value={line.grade_id}
                        onChange={(value) => updateLine(index, { grade_id: value })}
                        options={grades.map((grade) => ({
                          value: grade.id,
                          label: `${grade.code} · ${grade.name}`
                        }))}
                        placeholder={dict.jitSales.chooseGrade}
                        searchPlaceholder={locale === "id" ? "Cari grade..." : "Search grade..."}
                      />

                      <label className="block">
                        <span className="ops-label">{dict.jitSales.quantity}</span>
                        <input
                          type="number"
                          min="0"
                          step="0.001"
                          className="ops-input"
                          value={line.qty_planned}
                          onChange={(event) => updateLine(index, { qty_planned: event.target.value })}
                        />
                      </label>

                      <label className="block">
                        <span className="ops-label">{dict.jitSales.malPrice} ({form.company_currency_code})</span>
                        <input
                          type="number"
                          min="0"
                          step="0.01"
                          className="ops-input"
                          value={line.mal_unit_price}
                          onChange={(event) => updateLine(index, { mal_unit_price: event.target.value })}
                        />
                      </label>
                    </div>

                    <div className="mt-4 grid gap-4 md:grid-cols-3">
                      <label className="block">
                        <span className="ops-label">{dict.jitSales.sellingPrice} ({form.buyer_currency_code})</span>
                        <input
                          type="number"
                          min="0"
                          step="0.01"
                          className="ops-input"
                          value={line.selling_price_planned}
                          onChange={(event) =>
                            updateLine(index, { selling_price_planned: event.target.value })
                          }
                        />
                      </label>

                      <SearchableSelectField
                        label={dict.jitSales.agentOptional}
                        value={line.agent_id}
                        onChange={(value) => {
                          const nextAgent = agents.find((agent) => agent.id === value) ?? null;
                          updateLine(index, {
                            agent_id: value,
                            profit_share_scheme_id:
                              value && !line.profit_share_scheme_id && nextAgent
                                ? nextAgent.profit_share_scheme.id
                                : !value
                                  ? ""
                                  : line.profit_share_scheme_id
                          });
                        }}
                        options={agents.map((agent) => ({
                          value: agent.id,
                          label: `${agent.code} · ${agent.name}`
                        }))}
                        placeholder={dict.jitSales.noAgent}
                        searchPlaceholder={locale === "id" ? "Cari agen..." : "Search agent..."}
                      />

                      <SearchableSelectField
                        label={dict.jitSales.shareScheme}
                        value={line.profit_share_scheme_id}
                        onChange={(value) => updateLine(index, { profit_share_scheme_id: value })}
                        options={profitShareSchemes.map((scheme) => ({
                          value: scheme.id,
                          label: `${scheme.code} · ${scheme.name} (${formatDecimal(scheme.share_agent, locale)}%)`
                        }))}
                        placeholder={dict.jitSales.chooseScheme}
                        searchPlaceholder={locale === "id" ? "Cari skema..." : "Search scheme..."}
                        disabled={!line.agent_id}
                      />
                    </div>

                    <div className="mt-3.5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                      <SmallInfoCard
                        label={locale === "id" ? "Grade" : "Grade"}
                        value={selectedGrade ? `${selectedGrade.name}` : "-"}
                      />
                      <SmallInfoCard
                        label={dict.jitSales.plannedNominal}
                        value={formatCurrencyAmount(qty * sellingPrice, locale, form.buyer_currency_code)}
                      />
                      <SmallInfoCard
                        label={locale === "id" ? "Bagi hasil agen" : "Agent profit share"}
                        value={
                          selectedAgent && selectedScheme
                              ? `${selectedAgent.name} · ${formatDecimal(selectedScheme.share_agent, locale)}%`
                            : locale === "id" ? "Tidak ada" : "None"
                        }
                      />
                      <SmallInfoCard
                        label={dict.jitSales.plannedAgentCommission}
                        value={formatCurrencyAmount(previewCommission, locale, form.company_currency_code)}
                      />
                    </div>

                    <label className="mt-4 block">
                      <span className="ops-label">{locale === "id" ? "Catatan item" : "Item notes"}</span>
                      <textarea
                        className="ops-textarea min-h-[72px]"
                        value={line.notes}
                        onChange={(event) => updateLine(index, { notes: event.target.value })}
                        placeholder={locale === "id" ? "Opsional" : "Optional"}
                      />
                    </label>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="mt-5 grid gap-4 md:grid-cols-3">
            <SmallInfoCard
              label={dict.jitSales.totalNominal}
              value={formatCurrencyAmount(createSummary.total_nominal_buyer, locale, form.buyer_currency_code)}
            />
            <SmallInfoCard
              label={dict.jitSales.totalEquivalent}
              value={formatCurrencyAmount(createSummary.total_nominal_company, locale, form.company_currency_code)}
            />
            <SmallInfoCard
              label={dict.jitSales.totalAgentCommission}
              value={formatCurrencyAmount(createSummary.total_agent_commission, locale, form.company_currency_code)}
            />
          </div>

          <div className="mt-6 flex justify-end">
            <button type="button" className="ops-btn-primary" onClick={saveSale} disabled={saving}>
              {saving ? dict.common.processing : dict.jitSales.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.jitSales.listTitle}</p>
                <p className="ops-copy">{dict.jitSales.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.jitSales.noData}
                copy={dict.jitSales.noDataCopy}
              />
            ) : (
              <div className="overflow-x-auto">
                <table className="ops-table">
                  <thead>
                    <tr>
                      <th>{dict.jitSales.code}</th>
                      <th>{dict.jitSales.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)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {detailLoading ? (
            <div className="ops-card p-6 text-sm text-ink/60">{dict.jitSales.detailLoading}</div>
          ) : !detail ? (
            <div className="ops-card p-6 text-sm text-ink/60">{dict.jitSales.detailEmpty}</div>
          ) : (
            <div className="ops-card p-6">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="ops-overline">{dict.jitSales.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 space-y-4">
                <div className="grid gap-4 md:grid-cols-2">
                  <SmallInfoCard
                    label={dict.jitSales.buyer}
                    value={`${detail.buyer.code} · ${detail.buyer.name}`}
                  />
                  <SmallInfoCard
                    label={locale === "id" ? "Jasa Pengiriman" : "Courier"}
                    value={detail.courier ? `${detail.courier.code} · ${detail.courier.name}` : locale === "id" ? "Tidak ada" : "None"}
                  />
                </div>

                {detail.lines.map((line) => {
                  const closeLine = closeLines[line.id];
                  const rate = detail.exchange_rate ?? 1;
                  const actualSelling = Number(closeLine?.selling_price_actual || 0);
                  const commission =
                    ((actualSelling * rate - line.mal_unit_price) *
                      line.qty_planned *
                      (line.agent_share_percent ?? 0)) /
                    100;

                  return (
                    <div key={line.id} className="rounded-[24px] border border-line p-5">
                      <div className="flex flex-wrap items-start justify-between gap-4">
                        <div>
                          <h3 className="text-lg font-semibold tracking-tight text-ink">
                            {line.grade.code}
                          </h3>
                          <p className="mt-1 text-sm text-slate-500">{line.grade.name}</p>
                        </div>
                        <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
                          Qty {formatDecimal(line.qty_planned, locale)}
                        </span>
                      </div>

                      <div className="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                        <SmallInfoCard
                          label={dict.jitSales.malPrice}
                          value={formatCurrencyAmount(line.mal_unit_price, locale, detail.company_currency_code)}
                        />
                        <SmallInfoCard
                          label={dict.jitSales.sellingPrice}
                          value={formatCurrencyAmount(
                            line.selling_price_planned,
                            locale,
                            detail.buyer_currency_code
                          )}
                        />
                        <SmallInfoCard
                          label={locale === "id" ? "Agen" : "Agent"}
                          value={
                            line.agent
                              ? `${line.agent.name} · ${formatDecimal(line.agent_share_percent ?? 0, locale)}%`
                              : locale === "id" ? "Tidak ada" : "None"
                          }
                        />
                      <SmallInfoCard
                        label={dict.jitSales.actualNominal}
                        value={formatCurrencyAmount(
                          line.qty_planned * actualSelling,
                          locale,
                            detail.buyer_currency_code
                          )}
                        />
                      </div>

                      {detail.status === "OPEN" ? (
                        <div className="mt-4 grid gap-4 md:grid-cols-[180px_minmax(0,1fr)]">
                          <label className="block">
                            <span className="ops-label">{dict.jitSales.closeDate}</span>
                            <input
                              type="date"
                              className="ops-input"
                              value={closeDate}
                              onChange={(event) => setCloseDate(event.target.value)}
                            />
                          </label>

                          <label className="block">
                            <span className="ops-label">{dict.jitSales.actualSellingPrice} ({detail.buyer_currency_code})</span>
                            <input
                              type="number"
                              min="0"
                              step="0.01"
                              className="ops-input"
                              value={closeLine?.selling_price_actual ?? ""}
                              onChange={(event) =>
                                patchCloseLine(line.id, { selling_price_actual: event.target.value })
                              }
                            />
                          </label>
                        </div>
                      ) : null}

                      <div className="mt-4 rounded-2xl border border-line bg-slate-50 px-4 py-3 text-sm text-slate-600">
                        {locale === "id" ? "Rumus komisi agen:" : "Agent commission formula:"}{" "}
                        <span className="font-medium text-ink">
                          {locale === "id"
                            ? "((qty terjual × (harga jual aktual kurs perusahaan - harga MAL)) × persen share)"
                            : "((sold qty × (actual selling price at company rate - MAL price)) × share percent)"}
                        </span>
                        <div className="mt-2">
                          {locale === "id" ? "Estimasi komisi baris:" : "Estimated line commission:"}{" "}
                          <span className="font-semibold text-ink">
                            {formatCurrencyAmount(commission, locale, detail.company_currency_code)}
                          </span>
                        </div>
                      </div>
                    </div>
                  );
                })}

                {detail.status === "OPEN" ? (
                  <>
                    <label className="block">
                      <span className="ops-label">{dict.jitSales.uploadCloseReceipt}</span>
                      <input
                        type="file"
                        accept=".jpg,.jpeg,.png,.pdf"
                        className="ops-input pt-3"
                        onChange={(event) => setCloseReceiptFile(event.target.files?.[0] ?? null)}
                      />
                    </label>

                    <div className="grid gap-4 md:grid-cols-3">
                      <SmallInfoCard
                        label={dict.jitSales.totalBuyerNominal}
                        value={formatCurrencyAmount(closeSummary.totalNominalBuyer, locale, detail.buyer_currency_code)}
                      />
                      <SmallInfoCard
                        label={dict.jitSales.totalCompanyNominal}
                        value={formatCurrencyAmount(
                          closeSummary.totalNominalCompany,
                          locale,
                          detail.company_currency_code
                        )}
                      />
                      <SmallInfoCard
                        label={dict.jitSales.totalAgentCommission}
                        value={formatCurrencyAmount(
                          closeSummary.totalAgentCommission,
                          locale,
                          detail.company_currency_code
                        )}
                      />
                    </div>

                    <div className="flex justify-end">
                      <button
                        type="button"
                        className="ops-primary-btn"
                        onClick={closeSale}
                        disabled={closing}
                      >
                        {closing ? dict.common.processing : dict.jitSales.closeAll}
                      </button>
                    </div>
                  </>
                ) : (
                  <div className="grid gap-4 md:grid-cols-3">
                    <SmallInfoCard
                      label={dict.jitSales.totalBuyerNominal}
                      value={formatCurrencyAmount(detail.total_nominal_buyer, locale, detail.buyer_currency_code)}
                    />
                    <SmallInfoCard
                      label={dict.jitSales.totalCompanyNominal}
                      value={formatCurrencyAmount(detail.total_nominal_company, locale, detail.company_currency_code)}
                    />
                    <SmallInfoCard
                      label={dict.jitSales.totalAgentCommission}
                      value={formatCurrencyAmount(detail.total_agent_commission, locale, detail.company_currency_code)}
                    />
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
