import { Badge } from "@/components/ui/badge";
import { formatQuantityFixed } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

import { usdSignedAmount } from "../_lib/position-money";
import type { UnderlyingBreakEvenSummary } from "../_lib/underlying-break-even";

function fmt(value: number | null | undefined, digits = 2): string {
  if (value === null || value === undefined || !Number.isFinite(value)) return "—";
  return formatQuantityFixed(value, digits);
}

type Column = {
  key: string;
  currency: string;
  /** The column to compare against the strike (share currency). */
  primary: boolean;
  notional: number;
  coupons: number;
  breakEven: number | null;
};

type Scenario = {
  key: string;
  title: string;
  hint: string;
  columns: Column[];
};

function buildScenarios(summary: UnderlyingBreakEvenSummary): Scenario[] {
  const { source } = summary;
  const make = (
    key: string,
    title: string,
    hint: string,
    usd: { coupons: number; breakEven: number | null },
    original: { coupons: number; breakEven: number | null } | null,
  ): Scenario => {
    const columns: Column[] = [];
    if (source && original) {
      columns.push({
        key: `${key}-source`,
        currency: source.currency,
        primary: false,
        notional: source.notional,
        coupons: original.coupons,
        breakEven: original.breakEven,
      });
    }
    columns.push({
      key: `${key}-base`,
      currency: summary.currency,
      primary: true,
      notional: summary.structureNotional,
      coupons: usd.coupons,
      breakEven: usd.breakEven,
    });
    return { key, title, hint, columns };
  };

  return [
    make(
      "received",
      "Received",
      "Interest / dividend cash posted on the ledger",
      { coupons: summary.couponLedger, breakEven: summary.breakEvenLedger },
      source ? { coupons: source.couponLedger, breakEven: source.breakEvenLedger } : null,
    ),
    make(
      "assumed",
      "Total",
      "Also counts scheduled coupons that have no cash row yet (estimate)",
      { coupons: summary.couponWithPrior, breakEven: summary.breakEvenWithPrior },
      source ? { coupons: source.couponWithPrior, breakEven: source.breakEvenWithPrior } : null,
    ),
  ];
}

function Fact(props: { label: string; value: string; hint?: string; tone?: "warn" }) {
  return (
    <div className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-1.5">
      <div className="text-[10px] text-muted-foreground uppercase tracking-wide">{props.label}</div>
      <div
        className={cn(
          "font-semibold tabular-nums text-base leading-tight",
          props.tone === "warn" && "text-amber-700 dark:text-amber-300",
        )}
      >
        {props.value}
      </div>
      {props.hint ? <div className="text-[10px] text-muted-foreground">{props.hint}</div> : null}
    </div>
  );
}

export function UnderlyingBreakEvenPanel({ summary }: { summary: UnderlyingBreakEvenSummary }) {
  const scenarios = buildScenarios(summary);
  const hasSource = summary.source !== null;
  const ccy = summary.currency;
  const shareGap =
    summary.theoreticalQty !== null ? summary.deliveredQty - summary.theoreticalQty : null;
  const showLeftover = summary.tentative !== null && summary.tentative > 0.005;

  const rows: Array<{
    key: string;
    label: string;
    hint?: string;
    strong?: boolean;
    value: (column: Column) => string;
  }> = [
    { key: "notional", label: "Notional invested", value: (c) => usdSignedAmount(c.notional, c.currency) },
    { key: "coupons", label: "− Coupons", value: (c) => usdSignedAmount(c.coupons, c.currency) },
    {
      key: "net",
      label: "= Net cost",
      hint: "Notional − Coupons",
      value: (c) => usdSignedAmount(c.notional - c.coupons, c.currency),
    },
    { key: "shares", label: "÷ Shares delivered", value: () => fmt(summary.deliveredQty) },
    {
      key: "be",
      label: "Break-even per share",
      strong: true,
      value: (c) => usdSignedAmount(c.breakEven, c.currency, 4),
    },
  ];

  return (
    <div className="space-y-3 rounded-lg border border-border/60 bg-card px-3 py-2.5">
      <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
        <span className="font-medium text-sm">Break-even · {summary.underlyingName}</span>
        <span className="font-mono text-muted-foreground text-xs tracking-wide">
          {summary.underlyingIsin}
        </span>
        <Badge variant="outline" className="h-5 font-normal text-[10px]">
          {summary.lots.length} delivered lot{summary.lots.length === 1 ? "" : "s"}
        </Badge>
        {summary.excludedUndelivered > 0 ? (
          <Badge variant="outline" className="h-5 font-normal text-[10px] text-muted-foreground">
            {summary.excludedUndelivered} Live / undelivered excluded
          </Badge>
        ) : null}
      </div>

      <div className="grid grid-cols-2 gap-2 lg:grid-cols-4">
        <Fact
          label={`Strike${ccy ? ` (${ccy})` : ""}`}
          value={usdSignedAmount(summary.strike, ccy, 4)}
          hint="Price per share if delivered"
        />
        <Fact
          label="Shares expected"
          value={fmt(summary.theoreticalQty)}
          hint={hasSource ? `Notional in ${ccy} ÷ Strike` : "Notional ÷ Strike"}
        />
        <Fact
          label="Shares delivered"
          value={fmt(summary.deliveredQty)}
          hint={
            shareGap === null
              ? undefined
              : Math.abs(shareGap) < 0.005
                ? "Matches expected"
                : `${fmt(Math.abs(shareGap))} ${shareGap < 0 ? "fewer" : "more"} than expected`
          }
          tone={shareGap !== null && Math.abs(shareGap) >= 0.5 ? "warn" : undefined}
        />
        {showLeftover ? (
          <Fact
            label={`Leftover cash${ccy ? ` (${ccy})` : ""}`}
            value={usdSignedAmount(summary.tentative, ccy)}
            hint="Part-share paid in cash"
          />
        ) : null}
      </div>

      <div className="overflow-x-auto rounded-md border border-border/60">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-border/50 bg-muted/30">
              <th rowSpan={2} className="px-2 py-1.5 text-left align-bottom font-medium">
                How break-even is worked out
              </th>
              {scenarios.map((scenario, index) => (
                <th
                  key={scenario.key}
                  colSpan={scenario.columns.length}
                  className={cn(
                    "border-l border-border/50 px-2 py-1.5 text-center font-medium",
                    index === 1 && "bg-amber-600/5",
                  )}
                >
                  <div>{scenario.title}</div>
                  <div className="font-normal text-[10px] text-muted-foreground">{scenario.hint}</div>
                </th>
              ))}
            </tr>
            <tr className="border-b border-border/50 bg-muted/20 text-[11px] text-muted-foreground">
              {scenarios.flatMap((scenario) =>
                scenario.columns.map((column, columnIndex) => (
                  <th
                    key={column.key}
                    className={cn(
                      "px-2 py-1 text-right font-medium",
                      columnIndex === 0 && "border-l border-border/50",
                      column.primary && "text-foreground",
                    )}
                  >
                    {column.currency || "Amount"}
                    {hasSource && column.primary ? " (converted)" : ""}
                  </th>
                )),
              )}
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => (
              <tr
                key={row.key}
                className={cn(
                  "border-b border-border/40 last:border-b-0",
                  row.strong && "bg-emerald-600/5 font-semibold",
                )}
              >
                <td className="px-2 py-1.5">
                  {row.label}
                  {row.hint ? (
                    <span className="ml-1 font-normal text-[10px] text-muted-foreground">
                      {row.hint}
                    </span>
                  ) : null}
                </td>
                {scenarios.flatMap((scenario) =>
                  scenario.columns.map((column, columnIndex) => (
                    <td
                      key={`${row.key}-${column.key}`}
                      className={cn(
                        "px-2 py-1.5 text-right tabular-nums",
                        columnIndex === 0 && "border-l border-border/50",
                        !column.primary && "text-muted-foreground",
                        row.strong && column.primary && "text-sm text-emerald-800 dark:text-emerald-300",
                      )}
                    >
                      {row.value(column)}
                    </td>
                  )),
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p className="text-[11px] text-muted-foreground leading-snug">
        {summary.fxNotes.length > 0 && summary.source ? (
          <>
            The note is booked in {summary.source.currency}; the shares trade in {ccy}. {ccy}{" "}
            figures are converted at {summary.fxNotes.map((note) => note.replace(/^.*@ /, "")).join(", ")}{" "}
            ({summary.source.currency} → {ccy}, rate the note was booked at). Compare the{" "}
            <span className="font-medium text-foreground">{ccy}</span> break-even with the {ccy}{" "}
            strike; {summary.source.currency} is shown for reference.
          </>
        ) : null}
        {summary.fxMissing
          ? " No FX rate was found for some notes, so their amounts are shown unconverted."
          : null}
        {summary.lots.length > 1 ? ` Totals across ${summary.lots.length} lots.` : ""}
      </p>

      <div className="grid gap-2 lg:grid-cols-2">
        <div className="overflow-hidden rounded-md border border-emerald-600/20 bg-emerald-600/5">
          <div className="border-b border-emerald-600/15 px-2 py-1 font-medium text-[11px] text-emerald-900 dark:text-emerald-300">
            Included in break-even · {summary.lots.length}
          </div>
          <div className="max-h-48 overflow-auto">
            <table className="w-full text-[11px]">
              <thead className="bg-emerald-50 text-muted-foreground dark:bg-emerald-950/40">
                <tr>
                  <th className="px-1.5 py-0.5 text-left font-medium">Structure / Client</th>
                  <th className="px-1.5 py-0.5 text-right font-medium">Notional</th>
                  <th className="px-1.5 py-0.5 text-right font-medium">Received</th>
                  <th className="px-1.5 py-0.5 text-right font-medium">Assumed</th>
                  <th className="px-1.5 py-0.5 text-right font-medium">Shares</th>
                </tr>
              </thead>
              <tbody>
                {summary.lots.map((lot) => {
                  const converted = lot.fxRate !== 1;
                  const original = (value: number) =>
                    converted ? (
                      <div className="text-[10px] text-muted-foreground">
                        {lot.sourceCurrency} {fmt(value)}
                      </div>
                    ) : null;
                  return (
                    <tr
                      key={lot.positionKey || `${lot.structureIsin}-${lot.clientLabel}`}
                      className="border-t border-emerald-600/10"
                    >
                      <td className="px-1.5 py-1 align-top">
                        <div className="text-foreground leading-tight">{lot.structureName}</div>
                        <div className="font-mono text-[10px] text-muted-foreground tracking-wide">
                          {lot.structureIsin || "—"} · {lot.clientLabel}
                          {lot.statusLabel ? ` · ${lot.statusLabel}` : ""}
                        </div>
                      </td>
                      <td className="px-1.5 py-1 text-right align-top tabular-nums">
                        {usdSignedAmount(lot.notional, lot.currency)}
                        {original(lot.notionalSource)}
                      </td>
                      <td className="px-1.5 py-1 text-right align-top tabular-nums">
                        {usdSignedAmount(lot.couponLedger, lot.currency)}
                        {original(lot.couponLedgerSource)}
                      </td>
                      <td className="px-1.5 py-1 text-right align-top text-amber-900 tabular-nums dark:text-amber-300">
                        {lot.couponPrior > 0 ? usdSignedAmount(lot.couponPrior, lot.currency) : "—"}
                        {lot.couponPrior > 0 ? original(lot.couponPriorSource) : null}
                      </td>
                      <td className="px-1.5 py-1 text-right align-top tabular-nums">
                        {fmt(lot.deliveredQty)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {summary.lots.some((lot) => lot.fxRate !== 1) ? (
            <div className="border-t border-emerald-600/10 px-2 py-1 text-[10px] text-muted-foreground">
              Amounts in {ccy}; the grey line is the original {summary.source?.currency ?? "note currency"} amount.
            </div>
          ) : null}
        </div>

        <div className="overflow-hidden rounded-md border border-border/60 bg-muted/20">
          <div className="border-b border-border/50 px-2 py-1 font-medium text-[11px] text-muted-foreground">
            Excluded from break-even · {summary.excluded.length}
          </div>
          {summary.excluded.length === 0 ? (
            <p className="px-2 py-2 text-[11px] text-muted-foreground">
              No Live / undelivered holdings for this underlying.
            </p>
          ) : (
            <div className="max-h-48 overflow-auto">
              <table className="w-full text-[11px]">
                <thead className="bg-muted text-muted-foreground">
                  <tr>
                    <th className="px-1.5 py-0.5 text-left font-medium">Structure / Client</th>
                    <th className="px-1.5 py-0.5 text-left font-medium">Why excluded</th>
                  </tr>
                </thead>
                <tbody>
                  {summary.excluded.map((row) => (
                    <tr
                      key={row.positionKey || `${row.structureIsin}-${row.clientLabel}`}
                      className="border-t border-border/40"
                    >
                      <td className="px-1.5 py-1 align-top">
                        <div className="text-foreground leading-tight">{row.structureName}</div>
                        <div className="text-[10px] text-muted-foreground">
                          <span className="font-mono tracking-wide">{row.structureIsin || "—"}</span>
                          {" · "}
                          {row.clientLabel}
                          {row.statusLabel ? ` · ${row.statusLabel}` : ""}
                        </div>
                      </td>
                      <td className="px-1.5 py-1 align-top text-muted-foreground">{row.reason}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
