"use client";

import * as React from "react";

import { useFormContext, useWatch } from "react-hook-form";

import { fetchStockSecurityHoldingsClient } from "@/app/customer/[tenant]/stock/_lib/stock-api";
import type {
  StockSecurityHoldingPosition,
  StockSecurityHoldingsSummary,
} from "@/app/customer/[tenant]/stock/_lib/stock-holdings-types";
import { EM_DASH, formatAmount } from "@/lib/format/numbers";

import { SummaryRow } from "./transaction-form-summary";

const DEBOUNCE_MS = 400;

type StockHoldingsPanelProps = {
  excludeStockId?: string;
};

function formatOptionalAmount(value: number | null | undefined) {
  if (value === null || value === undefined || Number.isNaN(value)) return EM_DASH;
  return formatAmount(value);
}

function HoldingCard({ row }: { row: StockSecurityHoldingPosition }) {
  return (
    <li className="overflow-hidden rounded-lg border border-border/60 bg-muted/15">
      <div className="border-b border-border/40 px-4 py-3">
        <p className="font-medium text-sm">{row.bank_name || "—"}</p>
        <p className="mt-0.5 text-muted-foreground text-xs">
          {[row.currency_code || null, row.lot_count ? `${row.lot_count} lot${row.lot_count === 1 ? "" : "s"}` : null]
            .filter(Boolean)
            .join(" · ") || "—"}
        </p>
      </div>
      <div className="px-4 py-3">
        <SummaryRow label="Quantity" value={formatOptionalAmount(row.quantity)} mono />
        <SummaryRow label="Unit cost" value={formatOptionalAmount(row.unit_cost)} mono />
        <SummaryRow label="Net total" value={formatOptionalAmount(row.net_total)} mono />
      </div>
    </li>
  );
}

export function StockHoldingsPanel({ excludeStockId }: StockHoldingsPanelProps) {
  const { control } = useFormContext();
  const ticker = useWatch({ control, name: "ticker" });
  const bank = useWatch({ control, name: "bank" });
  const pCurrency = useWatch({ control, name: "p_currency" });

  const [positions, setPositions] = React.useState<StockSecurityHoldingPosition[]>([]);
  const [summary, setSummary] = React.useState<StockSecurityHoldingsSummary | null>(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const trimmedTicker = String(ticker ?? "").trim();

  React.useEffect(() => {
    if (!trimmedTicker) {
      setPositions([]);
      setSummary(null);
      setError(null);
      setLoading(false);
      return;
    }

    let cancelled = false;
    const timer = window.setTimeout(() => {
      void (async () => {
        setLoading(true);
        setError(null);

        try {
          const body: Record<string, unknown> = { ticker: trimmedTicker };
          if (bank) body.bank_id = bank;
          if (pCurrency) body.p_currency = pCurrency;
          if (excludeStockId) body.exclude_id = excludeStockId;

          const response = await fetchStockSecurityHoldingsClient(body);
          if (cancelled) return;

          setPositions(response.data?.positions ?? []);
          setSummary(response.data?.summary ?? null);
        } catch (err) {
          if (cancelled) return;
          setPositions([]);
          setSummary(null);
          setError(err instanceof Error ? err.message : "Could not load holdings.");
        } finally {
          if (!cancelled) setLoading(false);
        }
      })();
    }, DEBOUNCE_MS);

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [trimmedTicker, bank, pCurrency, excludeStockId]);

  if (!trimmedTicker) {
    return (
      <div className="px-5 py-8 text-center">
        <p className="font-medium text-sm">Enter a ticker</p>
        <p className="mt-1 text-muted-foreground text-sm">
          Existing holdings appear here once a security ticker is set.
        </p>
      </div>
    );
  }

  return (
    <div>
      <div className="border-b border-border/50 bg-muted/25 px-5 py-4">
        <p className="font-medium text-muted-foreground text-[11px] uppercase tracking-wider">
          Existing holdings
        </p>
        <p className="mt-2 font-mono font-semibold text-xl tracking-tight">{trimmedTicker}</p>
        {summary ? (
          <div className="mt-4 grid grid-cols-2 gap-3">
            <div className="rounded-lg border border-border/50 bg-background/60 px-3 py-2.5">
              <p className="text-muted-foreground text-[11px] uppercase tracking-wide">Quantity</p>
              <p className="mt-1 font-mono font-medium text-sm tabular-nums">
                {formatOptionalAmount(summary.quantity)}
              </p>
            </div>
            <div className="rounded-lg border border-border/50 bg-background/60 px-3 py-2.5">
              <p className="text-muted-foreground text-[11px] uppercase tracking-wide">Unit cost</p>
              <p className="mt-1 font-mono font-medium text-sm tabular-nums">
                {formatOptionalAmount(summary.unit_cost)}
              </p>
            </div>
          </div>
        ) : null}
      </div>

      {loading ? <p className="px-5 py-4 text-muted-foreground text-sm">Loading holdings…</p> : null}
      {error ? <p className="px-5 py-4 text-destructive text-sm">{error}</p> : null}

      {!loading && !error && positions.length === 0 ? (
        <div className="px-5 py-8 text-center">
          <p className="font-medium text-sm">No holdings found</p>
          <p className="mt-1 text-muted-foreground text-sm">
            {bank || pCurrency
              ? "Try clearing bank or currency filters to see all holdings for this ticker."
              : "There are no open positions for this security yet."}
          </p>
        </div>
      ) : null}

      {!loading && positions.length > 0 ? (
        <ul className="space-y-3 px-5 py-4">
          {positions.map((row) => (
            <HoldingCard key={`${row.bank_id}-${row.currency_id}`} row={row} />
          ))}
        </ul>
      ) : null}
    </div>
  );
}
