"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 { SearchableSelectField } from "@/components/shared/searchable-select-field";
import { formatCurrencyAmount, formatQuantity } from "@/lib/formatters";
import type { ApiErrorResponse } from "@/types/api";
import type {
  OfficeBuyoutAgentOption,
  OfficeBuyoutBootstrap,
  OfficeBuyoutListItem,
  OfficeBuyoutLotOption
} from "@/types/office-buyout";

type BuyoutLineForm = {
  source_lot_id: string;
  qty_buyout: string;
  buyout_unit_price: string;
  notes: string;
};

type BuyoutForm = {
  buyout_source_agent_id: string;
  purchase_date: string;
  notes: string;
  lines: BuyoutLineForm[];
};

const newLine = (): BuyoutLineForm => ({
  source_lot_id: "",
  qty_buyout: "",
  buyout_unit_price: "",
  notes: ""
});

const emptyForm = (): BuyoutForm => ({
  buyout_source_agent_id: "",
  purchase_date: new Date().toISOString().slice(0, 10),
  notes: "",
  lines: [newLine()]
});

function roundAmount(value: number) {
  return Number(value.toFixed(2));
}

function InfoCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="min-h-[92px] rounded border border-line/70 bg-slate-50/70 px-3.5 py-2.5">
      <p className="text-[10px] font-bold uppercase tracking-[0.06em] text-slate-500">{label}</p>
      <p className="mt-1 text-[11px] font-medium leading-5 text-ink break-words">{value}</p>
    </div>
  );
}

export function OfficeBuyoutClient({ currencyCode }: { currencyCode: string }) {
  const { locale } = useLocale();
  const searchParams = useSearchParams();
  const requestedId = searchParams.get("id");
  const [agents, setAgents] = useState<OfficeBuyoutAgentOption[]>([]);
  const [lots, setLots] = useState<OfficeBuyoutLotOption[]>([]);
  const [items, setItems] = useState<OfficeBuyoutListItem[]>([]);
  const [form, setForm] = useState<BuyoutForm>(emptyForm);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function loadAll() {
    setLoading(true);
    setError(null);
    try {
      const [bootstrapRes, itemsRes] = await Promise.all([
        fetch("/api/v1/purchases/office-buyout/bootstrap", { cache: "no-store" }),
        fetch("/api/v1/purchases/office-buyout", { cache: "no-store" })
      ]);

      const bootstrapPayload = (await bootstrapRes.json()) as { data: OfficeBuyoutBootstrap } | ApiErrorResponse;
      const itemsPayload = (await itemsRes.json()) as { data: OfficeBuyoutListItem[] } | ApiErrorResponse;

      if (!bootstrapRes.ok || !("data" in bootstrapPayload)) {
        throw new Error("message" in bootstrapPayload ? bootstrapPayload.message : "Gagal memuat master buyout.");
      }
      if (!itemsRes.ok || !("data" in itemsPayload)) {
        throw new Error("message" in itemsPayload ? itemsPayload.message : "Gagal memuat histori buyout.");
      }

      setAgents(bootstrapPayload.data.agents);
      setLots(bootstrapPayload.data.lots);
      setItems(itemsPayload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal memuat data buyout.");
    } finally {
      setLoading(false);
    }
  }

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

  const filteredLots = useMemo(
    () => lots.filter((lot) => lot.agent_id === form.buyout_source_agent_id),
    [form.buyout_source_agent_id, lots]
  );

  const selectedAgent = agents.find((agent) => agent.id === form.buyout_source_agent_id) ?? null;

  function resetForm() {
    setForm(emptyForm());
    setError(null);
  }

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

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

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

  async function saveBuyout() {
    setSubmitting(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/purchases/office-buyout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          buyout_source_agent_id: form.buyout_source_agent_id,
          purchase_date: form.purchase_date,
          notes: form.notes || null,
          lines: form.lines.map((line) => ({
            source_lot_id: line.source_lot_id,
            qty_buyout: Number(line.qty_buyout),
            buyout_unit_price: Number(line.buyout_unit_price),
            notes: line.notes || null
          }))
        })
      });

      const payload = (await response.json()) as { data?: OfficeBuyoutListItem; message?: string; errors?: Record<string, string[]> };
      if (!response.ok) {
        const firstError = payload.errors ? Object.values(payload.errors)[0]?.[0] : null;
        throw new Error(firstError ?? payload.message ?? "Gagal menyimpan buyout.");
      }

      resetForm();
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gagal menyimpan buyout.");
    } finally {
      setSubmitting(false);
    }
  }

  const totals = useMemo(() => {
    return form.lines.reduce(
      (acc, line) => {
        const sourceLot = lots.find((lot) => lot.id === line.source_lot_id) ?? null;
        const qty = Number(line.qty_buyout) || 0;
        const buyoutUnitPrice = Number(line.buyout_unit_price) || 0;
        const malPrice = sourceLot?.mal_unit_price ?? 0;
        const sharePercent = sourceLot?.agent_share_percent ?? 0;
        const buyoutAmount = qty * buyoutUnitPrice;
        const profitAmount = Math.max(0, qty * (buyoutUnitPrice - malPrice));
        const agentCommission = profitAmount * (sharePercent / 100);

        acc.totalQty += qty;
        acc.totalAmount += buyoutAmount;
        acc.totalAgentCommission += agentCommission;
        return acc;
      },
      { totalQty: 0, totalAmount: 0, totalAgentCommission: 0 }
    );
  }, [form.lines, lots]);
  const totalUnitCode = useMemo(() => {
    const unitCodes = Array.from(
      new Set(
        form.lines
          .map((line) => lots.find((lot) => lot.id === line.source_lot_id)?.unit_code ?? null)
          .filter(Boolean)
      )
    );
    return unitCodes.length === 1 ? unitCodes[0] : null;
  }, [form.lines, lots]);

  return (
    <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">{locale === "id" ? "Buyout kantor" : "Office buyout"}</p>
            <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">{locale === "id" ? "Pembelian Kantor / Buyout Agen" : "Office Purchase / Agent Buyout"}</h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              {locale === "id" ? "Ambil alih lot dari jalur agen menjadi stok milik kantor penuh. Buyout parsial akan mengurangi lot lama dan tetap membuat lot kantor baru." : "Take over lots from the agent channel into full office-owned stock. Partial buyouts reduce the old lot while still creating a new office lot."}
            </p>
          </div>
          <button type="button" onClick={resetForm} className="ops-btn-secondary">
            {locale === "id" ? "Reset formulir" : "Reset form"}
          </button>
        </div>

        <div className="mt-6 space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <SearchableSelectField
              label={locale === "id" ? "Agen sumber" : "Source agent"}
              value={form.buyout_source_agent_id}
              onChange={(value) =>
                setForm((current) => ({
                  ...current,
                  buyout_source_agent_id: value,
                  lines: current.lines.map((line) => ({ ...line, source_lot_id: "" }))
                }))
              }
              options={agents.map((agent) => ({ value: agent.id, label: `${agent.code} - ${agent.name}` }))}
              placeholder={locale === "id" ? "Pilih agen" : "Choose agent"}
              searchPlaceholder={locale === "id" ? "Cari agen..." : "Search agent..."}
            />
            <label className="block">
              <span className="ops-label">{locale === "id" ? "Tanggal buyout" : "Buyout date"}</span>
              <input
                type="date"
                value={form.purchase_date}
                onChange={(event) => setForm((current) => ({ ...current, purchase_date: event.target.value }))}
                className="ops-input"
              />
            </label>
          </div>

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

          <div className="rounded-lg border border-line/70 bg-slate-50/70 p-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-ink">{locale === "id" ? "Lot yang dibuyout" : "Lots to buy out"}</h3>
              <button type="button" onClick={addLine} className="ops-btn-secondary">
                {locale === "id" ? "Tambah lot" : "Add lot"}
              </button>
            </div>
            <div className="mt-4 space-y-4">
              {form.lines.map((line, index) => {
                const sourceLot = filteredLots.find((lot) => lot.id === line.source_lot_id) ?? null;
                const qtyBuyout = Number(line.qty_buyout) || 0;
                const buyoutUnitPrice = Number(line.buyout_unit_price) || 0;
                const profitAmount = sourceLot ? Math.max(0, qtyBuyout * (buyoutUnitPrice - sourceLot.mal_unit_price)) : 0;
                const agentCommission = sourceLot ? profitAmount * (sourceLot.agent_share_percent / 100) : 0;
                const remainingQty = sourceLot ? Math.max(0, sourceLot.available_qty - qtyBuyout) : 0;

                return (
                  <div key={`buyout-line-${index}`} className="rounded border border-line/70 bg-white p-3.5">
                    <div className="grid gap-3 xl:grid-cols-12 xl:items-start">
                      <div className="xl:col-span-6">
                        <SearchableSelectField
                          label={locale === "id" ? "Lot sumber" : "Source lot"}
                          value={line.source_lot_id}
                          onChange={(value) => updateLine(index, { source_lot_id: value })}
                          options={filteredLots.map((lot) => ({
                            value: lot.id,
                            label: `${lot.lot_code} · ${lot.grade} · ${formatQuantity(lot.available_qty, "id", lot.unit_code)}`
                          }))}
                          placeholder={selectedAgent ? (locale === "id" ? "Pilih lot aktif agen" : "Choose active agent lot") : (locale === "id" ? "Pilih agen dulu" : "Choose agent first")}
                          searchPlaceholder={locale === "id" ? "Cari lot..." : "Search lot..."}
                          disabled={!selectedAgent}
                        />
                      </div>
                      <div className="xl:col-span-3">
                        <label className="block">
                          <span className="mb-2 block min-h-[2.5rem] text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500">{`${locale === "id" ? "Qty buyout" : "Buyout qty"}${sourceLot ? ` (${sourceLot.unit_code})` : ""}`}</span>
                          <input
                            type="number"
                            value={line.qty_buyout}
                            onChange={(event) => updateLine(index, { qty_buyout: event.target.value })}
                            className="ops-input"
                          />
                        </label>
                      </div>
                      <div className="xl:col-span-3">
                        <label className="block">
                          <span className="mb-2 block min-h-[2.5rem] text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500">{locale === "id" ? "Harga buyout / unit" : "Buyout price / unit"}</span>
                          <input
                            type="number"
                            value={line.buyout_unit_price}
                            onChange={(event) => updateLine(index, { buyout_unit_price: event.target.value })}
                            className="ops-input"
                          />
                        </label>
                      </div>
                    </div>

                    {sourceLot ? (
                      <div className="mt-3.5 grid gap-2.5 md:grid-cols-2 xl:grid-cols-4">
                        <InfoCard label={locale === "id" ? "Grade" : "Grade"} value={sourceLot.grade} />
                        <InfoCard label={locale === "id" ? "Stok tersedia" : "Available stock"} value={formatQuantity(sourceLot.available_qty, locale, sourceLot.unit_code)} />
                        <InfoCard label={locale === "id" ? "Harga MAL" : "MAL price"} value={formatCurrencyAmount(sourceLot.mal_unit_price, locale, currencyCode, 0)} />
                        <InfoCard label={locale === "id" ? "Porsi agen" : "Agent share"} value={`${sourceLot.agent_share_percent}%`} />
                        <InfoCard label={locale === "id" ? "Gudang" : "Warehouse"} value={sourceLot.warehouse} />
                        <InfoCard label={locale === "id" ? "Lokasi" : "Location"} value={sourceLot.location ?? "-"} />
                        <InfoCard label={locale === "id" ? "Sisa lot lama" : "Remaining old lot"} value={formatQuantity(remainingQty, locale, sourceLot.unit_code)} />
                        <InfoCard label={locale === "id" ? "Komisi agen" : "Agent commission"} value={formatCurrencyAmount(roundAmount(agentCommission), locale, currencyCode, 0)} />
                      </div>
                    ) : null}

                    <label className="mt-3.5 block">
                      <span className="mb-2 block text-[11px] font-bold uppercase tracking-[0.06em] text-slate-500">{locale === "id" ? "Catatan baris" : "Line notes"}</span>
                      <textarea
                        rows={2}
                        value={line.notes}
                        onChange={(event) => updateLine(index, { notes: event.target.value })}
                        className="ops-textarea min-h-[72px]"
                      />
                    </label>

                    <div className="mt-3.5 flex flex-wrap items-end justify-between gap-3">
                      <p className="max-w-[calc(100%-72px)] text-[10px] leading-5 text-slate-500">
                        {locale === "id" ? "Profit agen dihitung: `max(0, qty * (harga buyout - harga MAL)) * persen share`" : "Agent profit formula: `max(0, qty * (buyout price - MAL price)) * share percent`"}
                      </p>
                      <button
                        type="button"
                        onClick={() => removeLine(index)}
                        className="inline-flex h-[52px] w-[52px] items-center justify-center rounded-xl border border-ember/30 bg-white text-ember transition hover:bg-ember/5"
                        aria-label="Hapus baris"
                        title="Hapus baris"
                      >
                        <Trash2 className="h-5 w-5" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="rounded border border-line/70 bg-slate-50 px-4 py-4">
            <div className="grid gap-3 md:grid-cols-3">
              <div>
                <p className="text-sm text-ink/60">{locale === "id" ? "Total qty buyout" : "Total buyout qty"}</p>
                <p className="text-xl font-semibold">
                  {formatQuantity(totals.totalQty, locale, totalUnitCode)}
                </p>
              </div>
              <div>
                <p className="text-sm text-ink/60">{locale === "id" ? "Total nilai buyout" : "Total buyout value"}</p>
                <p className="text-xl font-semibold">
                  {formatCurrencyAmount(roundAmount(totals.totalAmount), locale, currencyCode, 0)}
                </p>
              </div>
              <div>
                <p className="text-sm text-ink/60">{locale === "id" ? "Total komisi agen" : "Total agent commission"}</p>
                <p className="text-xl font-semibold">
                  {formatCurrencyAmount(roundAmount(totals.totalAgentCommission), locale, currencyCode, 0)}
                </p>
              </div>
            </div>
          </div>

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

          <button type="button" disabled={submitting} onClick={() => void saveBuyout()} className="ops-btn-primary">
            {submitting ? (locale === "id" ? "Menyimpan..." : "Saving...") : (locale === "id" ? "Simpan buyout kantor" : "Save office buyout")}
          </button>
        </div>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{locale === "id" ? "Histori Buyout Kantor" : "Office Buyout History"}</p>
            <p className="ops-copy">{locale === "id" ? "Riwayat pengambilalihan lot dari agen ke stok kantor." : "History of lot takeovers from agents into office stock."}</p>
          </div>
          <div className="ops-chip-muted">{items.length} {locale === "id" ? "buyout" : "buyouts"}</div>
        </div>
        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{locale === "id" ? "Memuat data buyout..." : "Loading buyout data..."}</div>
        ) : items.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">{locale === "id" ? "Belum ada transaksi buyout kantor." : "No office buyout transactions yet."}</div>
        ) : (
          <div className="divide-y divide-line/70">
            {items.map((item) => (
              <div
                key={item.id}
                className={`px-6 py-5 ${requestedId === item.id ? "bg-moss/5" : ""}`}
              >
                <div className="flex flex-wrap items-start justify-between gap-4">
                  <div>
                    <p className="text-lg font-semibold text-ink">{item.purchase_no}</p>
                    <p className="mt-1 text-sm text-slate-500">
                      {item.purchase_date} · {item.source_agent?.name ?? "-"}
                    </p>
                  </div>
                  <span className="ops-chip-active">{item.status}</span>
                </div>
                <div className="mt-4 grid gap-3 md:grid-cols-3">
                  <InfoCard
                    label={locale === "id" ? "Total qty" : "Total qty"}
                    value={formatQuantity(
                      item.total_qty,
                      locale,
                      new Set(item.lines.map((line) => line.unit_code)).size === 1 ? item.lines[0]?.unit_code ?? null : null
                    )}
                  />
                  <InfoCard label={locale === "id" ? "Nilai buyout" : "Buyout value"} value={formatCurrencyAmount(item.total_buyout_amount, locale, currencyCode, 0)} />
                  <InfoCard label={locale === "id" ? "Komisi agen" : "Agent commission"} value={formatCurrencyAmount(item.total_agent_commission, locale, currencyCode, 0)} />
                </div>
                <div className="mt-4 space-y-3">
                  {item.lines.map((line) => (
                    <div key={line.id} className="rounded border border-line/70 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
                      <div className="font-medium text-ink">
                        {line.source_lot_code} → {line.result_lot_code}
                      </div>
                      <div className="mt-1">
                        {line.grade} · {formatQuantity(line.qty_buyout, locale, line.unit_code)} · {locale === "id" ? "Harga buyout" : "Buyout price"} {formatCurrencyAmount(line.buyout_unit_price, locale, currencyCode, 0)}
                      </div>
                      <div className="mt-1 text-xs">
                        MAL {formatCurrencyAmount(line.mal_unit_price_snapshot, locale, currencyCode, 0)} · {locale === "id" ? "Porsi" : "Share"} {line.agent_share_percent}% · {locale === "id" ? "Komisi agen" : "Agent commission"} {formatCurrencyAmount(line.agent_commission, locale, currencyCode, 0)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
