"use client";

import { useState } from "react";
import type { LsegBond } from "@/hooks/useLsegCredit";
import { BondRiskBadge } from "./BondRiskBadge";

type SortKey = "composite_score" | "coupon" | "ytm" | "spread";

const SORTABLE_COLS: { key: SortKey; label: string }[] = [
  { key: "composite_score", label: "Risk Score" },
  { key: "coupon",          label: "Coupon (%)" },
  { key: "ytm",             label: "YTM (%)" },
  { key: "spread",          label: "Spread (bps)" },
];

function fmt(val: number | null | undefined, decimals = 2): string {
  return val != null ? val.toFixed(decimals) : "—";
}

function spreadVal(bond: LsegBond): number | null {
  return bond.z_spread ?? bond.asset_swap_spread ?? null;
}

function spreadLabel(bond: LsegBond): string {
  if (bond.z_spread != null) return fmt(bond.z_spread, 0);
  if (bond.asset_swap_spread != null) return fmt(bond.asset_swap_spread, 0) + "*";
  return "—";
}

function SortButton({
  label,
  active,
  asc,
  onClick,
}: {
  label: string;
  active: boolean;
  asc: boolean;
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-0.5 text-xs font-medium transition-colors ${
        active ? "text-foreground" : "text-muted-foreground hover:text-foreground"
      }`}
    >
      {label}
      <span className="ml-0.5 opacity-60">{active ? (asc ? "↑" : "↓") : ""}</span>
    </button>
  );
}

export function BondRiskTable({ bonds }: { bonds: LsegBond[] }) {
  const [sortKey, setSortKey] = useState<SortKey>("composite_score");
  const [asc, setAsc] = useState(true);

  function handleSort(key: SortKey) {
    if (key === sortKey) {
      setAsc((p) => !p);
    } else {
      setSortKey(key);
      setAsc(true);
    }
  }

  const sorted = [...bonds].sort((a, b) => {
    let av: number, bv: number;
    if (sortKey === "composite_score") {
      av = a.risk.composite_score;
      bv = b.risk.composite_score;
    } else if (sortKey === "spread") {
      av = spreadVal(a) ?? -Infinity;
      bv = spreadVal(b) ?? -Infinity;
    } else {
      const key = sortKey as "coupon" | "ytm";
      av = (a[key] ?? -Infinity) as number;
      bv = (b[key] ?? -Infinity) as number;
    }
    return asc ? av - bv : bv - av;
  });

  const hasAswFallback = bonds.some(
    (b) => b.z_spread == null && b.asset_swap_spread != null
  );

  return (
    <div className="space-y-1">
      <div className="overflow-x-auto rounded-xl border border-border">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/20">
              <th className="px-4 py-2.5 text-left text-xs font-medium text-muted-foreground">
                Bond / Issuer
              </th>
              {SORTABLE_COLS.map((col) => (
                <th key={col.key} className="px-4 py-2.5 text-right">
                  <div className="flex justify-end">
                    <SortButton
                      label={col.label}
                      active={sortKey === col.key}
                      asc={asc}
                      onClick={() => handleSort(col.key)}
                    />
                  </div>
                </th>
              ))}
              <th className="px-4 py-2.5 text-right text-xs font-medium text-muted-foreground">
                Rating
              </th>
              <th className="px-4 py-2.5 text-right text-xs font-medium text-muted-foreground">
                Currency
              </th>
              <th className="px-4 py-2.5 text-right text-xs font-medium text-muted-foreground">
                Maturity
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {sorted.map((bond, i) => (
              <tr key={bond.isin ?? i} className="hover:bg-muted/10 transition-colors">
                <td className="px-4 py-2.5">
                  <p className="font-medium">{bond.name ?? bond.isin ?? "—"}</p>
                  <p className="text-xs text-muted-foreground">{bond.issuer ?? "—"}</p>
                </td>
                <td className="px-4 py-2.5 text-right">
                  <BondRiskBadge risk={bond.risk} />
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {fmt(bond.coupon)}
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {fmt(bond.ytm)}
                </td>
                <td className="px-4 py-2.5 text-right tabular-nums">
                  {spreadLabel(bond)}
                </td>
                <td className="px-4 py-2.5 text-right text-xs tabular-nums">
                  {bond.rating_moodys ?? "—"}
                </td>
                <td className="px-4 py-2.5 text-right text-xs text-muted-foreground">
                  {bond.currency ?? "—"}
                </td>
                <td className="px-4 py-2.5 text-right text-xs text-muted-foreground">
                  {bond.maturity_date ?? "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {sorted.length === 0 && (
          <p className="px-4 py-8 text-center text-sm text-muted-foreground">
            No bond data available. Check that the LSEG session is active.
          </p>
        )}
      </div>
      {hasAswFallback && (
        <p className="text-xs text-muted-foreground px-1">
          * Asset swap spread shown where Z-spread is unavailable.
        </p>
      )}
    </div>
  );
}
