"use client";

import * as React from "react";
import { Loader2 } from "lucide-react";

import { cn } from "@/lib/utils";

import { fetchLiquidityIndividualClient } from "../_lib/liquidity-individual-api";
import type {
  LiquidityComponentId,
  LiquidityIndividualData,
  LiquidityIndividualTransactionTable,
} from "../_lib/liquidity-individual-types";

export type LiquidityDetailTarget = {
  currency: string;
  currencyName?: string;
  component: LiquidityComponentId;
  componentLabel: string;
  customerId?: number | null;
  customerName?: string | null;
  bankName?: string | null;
};

function InfoChip({
  label,
  value,
  detail,
  mono,
}: {
  label: string;
  value: string;
  detail?: string;
  mono?: boolean;
}) {
  return (
    <div className="min-w-0 rounded-xl border border-border/60 bg-card/80 px-3 py-2 shadow-sm backdrop-blur-sm">
      <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
      <p
        className={cn(
          "mt-0.5 truncate text-sm font-medium text-foreground",
          mono && "font-mono tracking-tight",
        )}
        title={value}
      >
        {value}
      </p>
      {detail ? (
        <p className="mt-0.5 truncate text-xs text-muted-foreground" title={detail}>
          {detail}
        </p>
      ) : null}
    </div>
  );
}

function TransactionTable({
  table,
  title,
  emptyLabel,
}: {
  table: LiquidityIndividualTransactionTable | null | undefined;
  title: string;
  emptyLabel: string;
}) {
  const rows = table?.rows ?? [];
  if (rows.length === 0) {
    return (
      <div className="space-y-2">
        <p className="text-sm font-medium">{title}</p>
        <p className="rounded-xl border border-dashed border-border/60 px-3 py-6 text-center text-sm text-muted-foreground">
          {emptyLabel}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <p className="text-sm font-medium">{title}</p>
      <div className="overflow-x-auto rounded-xl border border-border/60 bg-card shadow-sm">
        <table className="w-full min-w-[800px] border-collapse text-sm">
          <thead>
            <tr className="bg-sky-950 text-primary-foreground">
              <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
                Ref ID
              </th>
              <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
                Bank Name
              </th>
              <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
                Trade Date
              </th>
              <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                Quantity
              </th>
              <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                Price
              </th>
              <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                Purchase Value
              </th>
              <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                Purchase Value (RC)
              </th>
              <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
                Market Value (RC)
              </th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row, index) => (
              <tr
                key={`${row.refId}-${index}`}
                className={cn("border-t border-border/60", index % 2 === 1 && "bg-muted/20")}
              >
                <td className="px-3 py-2">{row.refId || "—"}</td>
                <td className="px-3 py-2">{row.bankName}</td>
                <td className="px-3 py-2">{row.tradeDate || "—"}</td>
                <td className="px-3 py-2 text-right tabular-nums">{row.quantityFmt}</td>
                <td className="px-3 py-2 text-right tabular-nums">{row.priceFmt}</td>
                <td className="px-3 py-2 text-right tabular-nums">{row.purchaseValueFmt}</td>
                <td className="px-3 py-2 text-right tabular-nums">{row.purchaseValueRcFmt}</td>
                <td className="px-3 py-2 text-right tabular-nums">{row.marketValueRcFmt}</td>
              </tr>
            ))}
            {table?.totals ? (
              <tr className="border-t border-border bg-muted/50 font-semibold">
                <td className="px-3 py-2.5 text-right" colSpan={3}>
                  Total
                </td>
                <td className="px-3 py-2.5 text-right tabular-nums">{table.totals.quantityFmt}</td>
                <td className="px-3 py-2.5" />
                <td className="px-3 py-2.5 text-right tabular-nums">{table.totals.purchaseValueFmt}</td>
                <td className="px-3 py-2.5 text-right tabular-nums">{table.totals.purchaseValueRcFmt}</td>
                <td className="px-3 py-2.5 text-right tabular-nums">{table.totals.marketValueRcFmt}</td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function targetKey(target: LiquidityDetailTarget | null): string {
  if (!target) return "";
  return [target.currency, target.component, target.customerId ?? "", target.bankName?.trim() ?? ""].join(
    "\0",
  );
}

/** In-sheet Cash / Call / Fixed / Leverage transaction detail for Liquidity Report. */
export function LiquidityDetailPanel({
  active,
  target,
  onExit,
  exitLabel = "← Back to currency breakdown",
}: {
  active: boolean;
  target: LiquidityDetailTarget | null;
  onExit: () => void;
  exitLabel?: string;
}) {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [data, setData] = React.useState<LiquidityIndividualData | null>(null);
  const cacheKey = targetKey(target);

  React.useEffect(() => {
    if (!active || !target) {
      setData(null);
      setError(null);
      setLoading(false);
      return;
    }

    const controller = new AbortController();
    const customerId =
      target.customerId != null && Number.isFinite(target.customerId) && target.customerId > 0
        ? target.customerId
        : null;

    setLoading(true);
    setError(null);
    setData(null);

    fetchLiquidityIndividualClient(
      {
        currency: target.currency,
        component: target.component,
        customerId,
        bankName: target.bankName?.trim() || null,
      },
      controller.signal,
    )
      .then((result) => setData(result))
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        setError(err instanceof Error ? err.message : "Could not load liquidity detail.");
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });

    return () => controller.abort();
  }, [active, cacheKey]); // eslint-disable-line react-hooks/exhaustive-deps -- target encoded in cacheKey

  const bankLabel =
    target?.bankName?.trim() || (data && data.bankNames.length > 0 ? data.bankNames.join(", ") : "—");
  const currencyCode = target?.currency ?? data?.isin ?? "—";
  const currencyName = target?.currencyName?.trim() || data?.currencyName || "";

  return (
    <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto">
      <section className="flex flex-col gap-3 rounded-2xl border border-border/60 bg-card p-3 shadow-sm">
        <button
          type="button"
          className="w-fit text-sm text-primary underline-offset-2 hover:underline"
          onClick={onExit}
        >
          {exitLabel}
        </button>

        <div className="grid gap-2 sm:grid-cols-3">
          <InfoChip label="Bank Name" value={bankLabel} />
          <InfoChip
            label="Customer"
            value={`${data?.customerLabel || target?.customerName || "—"}${data?.refIdsSuffix || ""}`}
          />
          <InfoChip
            label="Currency"
            value={currencyCode}
            detail={[target?.componentLabel, currencyName].filter(Boolean).join(" · ") || undefined}
            mono
          />
        </div>
      </section>

      {loading ? (
        <div className="flex items-center gap-2 py-10 text-sm text-muted-foreground">
          <Loader2 className="size-4 animate-spin" />
          Loading…
        </div>
      ) : null}

      {error ? <p className="text-sm text-destructive">{error}</p> : null}

      {!loading && !error && data ? (
        <div className="space-y-6">
          <TransactionTable
            table={data.currentHoldings}
            title="Active"
            emptyLabel="No active holdings."
          />
          <TransactionTable
            table={data.history}
            title="History"
            emptyLabel="No history."
          />
        </div>
      ) : null}
    </div>
  );
}
