"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";

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

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

function formatQty(value: number, locale: string) {
  return formatNumber(value, locale, 3);
}

function formatCurrency(value: number, locale: string, currencyCode: string) {
  return formatCurrencyAmount(value, locale, currencyCode, 2);
}

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

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

function resolveStatusTone(status: string) {
  if (status === "CLOSED") return "teal" as const;
  if (status === "READY_TO_CLOSE") return "warning" as const;
  return "default" as const;
}

function formatEventLabel(eventType: string) {
  return eventType.replaceAll("_", " ");
}

function resolveEventHref(
  entry: PurchaseRealizationEntryItem,
  purchaseType: string
) {
  if (!entry.reference_id) return null;

  if (entry.reference_type === "REGULAR_SALE") {
    return `/sales-regular?id=${entry.reference_id}`;
  }
  if (entry.reference_type === "CONSIGNMENT") {
    return `/consignments?id=${entry.reference_id}`;
  }
  if (entry.reference_type === "LOT_WASHING") {
    return `/washing?id=${entry.reference_id}`;
  }
  if (entry.reference_type === "PURCHASE") {
    return purchaseType === "OFFICE_BUYOUT" || entry.event_type === "OFFICE_BUYOUT_REVENUE"
      ? `/purchases/office-buyout?id=${entry.reference_id}`
      : `/purchases?id=${entry.reference_id}`;
  }

  return null;
}

function EntryRow({
  entry,
  currencyCode,
  purchaseType
}: {
  entry: PurchaseRealizationEntryItem;
  currencyCode: string;
  purchaseType: string;
}) {
  const { locale, dict } = useLocale();
  const eventHref = resolveEventHref(entry, purchaseType);

  return (
    <div className="rounded-[22px] border border-line/70 bg-white px-5 py-4">
      <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
        <div>
          <div className="text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">
            {formatEventLabel(entry.event_type)}
          </div>
          <div className="mt-1 text-sm font-semibold text-ink">
            {entry.lot_code ?? "-"} · {entry.reference_type}
          </div>
          <div className="mt-1 text-xs text-slate-500">
            {new Date(entry.occurred_at).toLocaleString(locale === "id" ? "id-ID" : "en-US")}
          </div>
          {eventHref ? (
            <Link href={eventHref} className="mt-2 inline-flex text-xs font-semibold text-moss hover:underline">
              {dict.purchaseRealizationModule.openSource}
            </Link>
          ) : null}
          {entry.notes ? <div className="mt-2 text-sm text-slate-600">{entry.notes}</div> : null}
        </div>
        <div className="grid min-w-[320px] grid-cols-2 gap-3 text-sm md:grid-cols-4">
          <InfoMini label={dict.purchaseRealizationModule.qtyIn} value={formatQty(entry.qty_in, locale)} />
          <InfoMini label={dict.purchaseRealizationModule.qtyOut} value={formatQty(entry.qty_out, locale)} />
          <InfoMini label={dict.purchaseRealizationModule.shrinkage} value={formatQty(entry.qty_shrinkage, locale)} />
          <InfoMini label={dict.purchaseRealizationModule.agentProfit} value={formatCurrency(entry.agent_amount, locale, currencyCode)} />
          <InfoMini label={dict.purchaseRealizationModule.cost} value={formatCurrency(entry.amount_cost, locale, currencyCode)} />
          <InfoMini label={dict.purchaseRealizationModule.revenue} value={formatCurrency(entry.amount_revenue, locale, currencyCode)} />
          <InfoMini label={dict.purchaseRealizationModule.expense} value={formatCurrency(entry.amount_expense, locale, currencyCode)} />
          <InfoMini label={dict.purchaseRealizationModule.profit} value={formatCurrency(entry.amount_profit, locale, currencyCode)} />
        </div>
      </div>
    </div>
  );
}

function InfoMini({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-2xl border border-line/60 bg-slate-50 px-3 py-2">
      <div className="text-[10px] font-bold uppercase tracking-[0.08em] text-slate-500">{label}</div>
      <div className="mt-1 text-sm font-semibold text-ink">{value}</div>
    </div>
  );
}

type PurchaseRealizationClientProps = {
  currencyCode: string;
};

export function PurchaseRealizationClient({
  currencyCode
}: PurchaseRealizationClientProps) {
  const { locale, dict } = useLocale();
  const [items, setItems] = useState<PurchaseRealizationListItem[]>([]);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("ALL");
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<PurchaseRealizationDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [detailLoading, setDetailLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

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

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

  const filteredItems = useMemo(() => {
    const normalizedSearch = search.trim().toLowerCase();
    return items.filter((item) => {
      const matchesStatus = statusFilter === "ALL" || item.status === statusFilter;
      if (!matchesStatus) return false;
      if (!normalizedSearch) return true;

      const haystack = [
        item.purchase_no,
        item.purchase_type,
        item.supplier_name,
        item.status
      ]
        .join(" ")
        .toLowerCase();

      return haystack.includes(normalizedSearch);
    });
  }, [items, search, statusFilter]);

  const statusOptions = useMemo(() => {
    return ["ALL", ...Array.from(new Set(items.map((item) => item.status)))];
  }, [items]);

  useEffect(() => {
    if (filteredItems.length === 0) {
      setSelectedId(null);
      setDetail(null);
      return;
    }

    if (!selectedId || !filteredItems.some((item) => item.purchase_id === selectedId)) {
      void openDetail(filteredItems[0].purchase_id);
    }
  }, [filteredItems, selectedId]);

  const statCards = useMemo(() => {
    if (!detail) return [];
    return [
      {
        label: "Qty tersisa",
        value: formatQty(detail.summary.qty_remaining, locale),
        hint: `Awal ${formatQty(detail.summary.qty_opening, locale)}`
      },
      {
        label: dict.purchaseRealizationModule.revenue,
        value: formatCurrency(detail.summary.revenue_total, locale, currencyCode),
        hint: `${dict.purchaseRealizationModule.openingCost} ${formatCurrency(detail.summary.cost_opening_total, locale, currencyCode)}`
      },
      {
        label: dict.purchaseRealizationModule.profitLoss,
        value: formatCurrency(detail.summary.profit_loss_total, locale, currencyCode),
        hint: `${dict.purchaseRealizationModule.additionalCost} ${formatCurrency(detail.summary.cost_additional_total, locale, currencyCode)}`
      },
      {
        label: dict.purchaseRealizationModule.agentProfit,
        value: formatCurrency(detail.summary.agent_profit_total, locale, currencyCode),
        hint:
          detail.summary.agent_share_percent === null
            ? dict.purchaseRealizationModule.noAgentScheme
            : `Porsi ${formatNumber(detail.summary.agent_share_percent, locale, 2)}%`
      }
    ];
  }, [currencyCode, detail, dict.purchaseRealizationModule, locale]);

  return (
    <div className="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
      <section className="overflow-hidden rounded-[28px] border border-line/70 bg-white shadow-sm">
        <div className="flex items-center justify-between border-b border-line/70 px-6 py-5">
          <div>
            <h2 className="text-lg font-semibold text-ink">{dict.purchaseRealizationModule.listTitle}</h2>
            <p className="text-sm text-slate-500">{dict.purchaseRealizationModule.listCopy}</p>
          </div>
          <div className="ops-chip-muted">{filteredItems.length} / {items.length} pembelian</div>
        </div>
        <div className="grid gap-3 border-b border-line/60 px-6 py-4 md:grid-cols-[1fr_180px]">
          <label className="block">
            <span className="mb-1 block text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">
              {dict.purchaseRealizationModule.searchLabel}
            </span>
            <input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              placeholder={dict.purchaseRealizationModule.searchPlaceholder}
              className="w-full rounded-2xl border border-line/70 bg-white px-4 py-2.5 text-sm text-ink outline-none transition focus:border-moss/60"
            />
          </label>
          <label className="block">
            <span className="mb-1 block text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">
              Status
            </span>
            <select
              value={statusFilter}
              onChange={(event) => setStatusFilter(event.target.value)}
              className="w-full rounded-2xl border border-line/70 bg-white px-4 py-2.5 text-sm text-ink outline-none transition focus:border-moss/60"
            >
              {statusOptions.map((status) => (
                <option key={status} value={status}>
                  {status === "ALL" ? dict.purchaseRealizationModule.allStatuses : status}
                </option>
              ))}
            </select>
          </label>
        </div>
        {loading ? (
          <div className="px-6 py-8 text-sm text-slate-500">{dict.common.loading}</div>
        ) : filteredItems.length === 0 ? (
          <EmptyState
            title={dict.purchaseRealizationModule.noResults}
            copy={dict.purchaseRealizationModule.noResultsCopy}
          />
        ) : (
          <div className="divide-y divide-line/60">
            {filteredItems.map((item) => (
              <button
                key={item.purchase_id}
                type="button"
                onClick={() => void openDetail(item.purchase_id)}
                className={`flex w-full flex-col gap-3 px-6 py-5 text-left transition hover:bg-slate-50 ${
                  selectedId === item.purchase_id ? "bg-slate-50" : "bg-white"
                }`}
              >
                <div className="flex items-center justify-between gap-4">
                  <div>
                    <div className="text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">
                      {item.purchase_type}
                    </div>
                    <div className="mt-1 text-xl font-semibold text-ink">{item.purchase_no}</div>
                    <div className="mt-1 text-sm text-slate-500">
                      {item.supplier_name} · {new Date(item.purchase_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")}
                    </div>
                  </div>
                  <span className="rounded-full border border-line/70 px-3 py-1 text-xs font-semibold uppercase tracking-[0.08em] text-slate-600">
                    {item.status}
                  </span>
                </div>
                <div className="grid grid-cols-2 gap-3 text-sm md:grid-cols-4">
                  <InfoMini label={dict.purchaseRealizationModule.qtyRemaining} value={formatQty(item.qty_remaining, locale)} />
                  <InfoMini label={dict.purchaseRealizationModule.revenue} value={formatCurrency(item.revenue_total, locale, currencyCode)} />
                  <InfoMini label={dict.purchaseRealizationModule.profitLoss} value={formatCurrency(item.profit_loss_total, locale, currencyCode)} />
                  <InfoMini label={dict.purchaseRealizationModule.agentProfit} value={formatCurrency(item.agent_profit_total, locale, currencyCode)} />
                </div>
              </button>
            ))}
          </div>
        )}
      </section>

      <section className="overflow-hidden rounded-[28px] border border-line/70 bg-white shadow-sm">
        {!detail ? (
          <EmptyState
            title={dict.purchaseRealizationModule.emptyDetail}
            copy={dict.purchaseRealizationModule.emptyDetailCopy}
          />
        ) : (
          <div className="space-y-6 px-6 py-6">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">
                  {dict.purchaseRealizationModule.overline}
                </div>
                <h2 className="mt-3 text-[38px] font-semibold leading-none text-ink">
                  {detail.purchase.purchase_no}
                </h2>
                <p className="mt-4 text-base text-slate-500">
                  {detail.purchase.supplier_name} · {new Date(detail.purchase.purchase_date).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")} ·
                  {` ${detail.purchase.purchase_type}`}
                </p>
              </div>
              <div className={`rounded-3xl border px-5 py-4 ${resolveStatusTone(detail.summary.status) === "teal" ? "border-moss/70 bg-moss text-white" : resolveStatusTone(detail.summary.status) === "warning" ? "border-amber-200 bg-amber-50 text-amber-900" : "border-line/70 bg-slate-50 text-ink"}`}>
                <div className="text-[11px] font-bold uppercase tracking-[0.08em] opacity-70">{dict.purchaseRealizationModule.closingStatus}</div>
                <div className="mt-2 text-2xl font-semibold">{detail.summary.status}</div>
                <div className="mt-2 text-sm opacity-80">
                  {detail.summary.closed_at
                    ? `${dict.purchaseRealizationModule.closedOn} ${new Date(detail.summary.closed_at).toLocaleDateString(locale === "id" ? "id-ID" : "en-US")}`
                    : detail.purchase.profit_share_scheme_name ?? dict.purchaseRealizationModule.noAgentScheme}
                </div>
              </div>
            </div>

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

            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
              {statCards.map((card) => (
                <StatCard key={card.label} label={card.label} value={card.value} hint={card.hint} />
              ))}
            </div>

            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
              <StatCard label={dict.purchaseRealizationModule.qtySold} value={formatQty(detail.summary.qty_sold, locale)} />
              <StatCard label={dict.purchaseRealizationModule.qtyReturned} value={formatQty(detail.summary.qty_returned, locale)} />
              <StatCard label={dict.purchaseRealizationModule.qtyShrinkage} value={formatQty(detail.summary.qty_shrinkage, locale)} />
              <StatCard label={dict.purchaseRealizationModule.agentShare} value={detail.summary.agent_share_percent === null ? "-" : formatNumber(detail.summary.agent_share_percent, locale, 2)} />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="rounded-[26px] border border-line/70 bg-slate-50 px-5 py-5">
                <div className="text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">{dict.purchaseRealizationModule.purchaseInfo}</div>
                <div className="mt-4 space-y-2 text-sm text-slate-600">
                  <div>Agen: {detail.purchase.agent_name ?? "-"}</div>
                  <div>Agen sumber buyout: {detail.purchase.buyout_source_agent_name ?? "-"}</div>
                  <div>Skema bagi hasil: {detail.purchase.profit_share_scheme_name ?? "-"}</div>
                  <div>Porsi agen: {detail.purchase.share_agent_percent === null ? "-" : `${formatNumber(detail.purchase.share_agent_percent, locale, 2)}%`}</div>
                </div>
              </div>
              <div className="rounded-[26px] border border-line/70 bg-slate-50 px-5 py-5">
                <div className="text-[11px] font-bold uppercase tracking-[0.08em] text-slate-500">{dict.purchaseRealizationModule.financialSummary}</div>
                <div className="mt-4 space-y-2 text-sm text-slate-600">
                  <div>{dict.purchaseRealizationModule.openingCost}: {formatCurrency(detail.summary.cost_opening_total, locale, currencyCode)}</div>
                  <div>{dict.purchaseRealizationModule.additionalCost}: {formatCurrency(detail.summary.cost_additional_total, locale, currencyCode)}</div>
                  <div>{dict.purchaseRealizationModule.totalRevenue}: {formatCurrency(detail.summary.revenue_total, locale, currencyCode)}</div>
                  <div>{dict.purchaseRealizationModule.profitLoss}: {formatCurrency(detail.summary.profit_loss_total, locale, currencyCode)}</div>
                </div>
              </div>
            </div>

            <div>
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold text-ink">{dict.purchaseRealizationModule.eventTimeline}</h3>
                {detailLoading ? <div className="text-sm text-slate-500">{dict.purchaseRealizationModule.loadingDetail}</div> : null}
              </div>
              <div className="mt-4 space-y-3">
                {detail.entries.length === 0 ? (
                  <EmptyState
                    title={dict.purchaseRealizationModule.noEvents}
                    copy={dict.purchaseRealizationModule.noEventsCopy}
                  />
                ) : (
                  detail.entries.map((entry) => (
                    <EntryRow
                      key={entry.id}
                      entry={entry}
                      currencyCode={currencyCode}
                      purchaseType={detail.purchase.purchase_type}
                    />
                  ))
                )}
              </div>
            </div>
          </div>
        )}
      </section>
    </div>
  );
}
