import type { LsegPortfolioSummary } from "@/hooks/useLsegCredit";

const GRADE_ORDER = ["LOW RISK", "MODERATE RISK", "ELEVATED RISK", "HIGH RISK"] as const;

const GRADE_BAR_COLOR: Record<string, string> = {
  "LOW RISK":      "bg-green-500",
  "MODERATE RISK": "bg-yellow-500",
  "ELEVATED RISK": "bg-orange-500",
  "HIGH RISK":     "bg-red-500",
};

function StatCard({ label, value }: { label: string; value: string | number | null }) {
  return (
    <div className="rounded-xl border border-border bg-muted/20 px-4 py-3">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="mt-0.5 text-lg font-bold">
        {value != null ? value : <span className="text-muted-foreground">—</span>}
      </p>
    </div>
  );
}

export function PortfolioSummary({ data }: { data: LsegPortfolioSummary }) {
  const total = data.total_bonds || 1;

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Total Bonds" value={data.total_bonds} />
        <StatCard
          label="Avg. Risk Score"
          value={data.avg_composite_score != null ? data.avg_composite_score.toFixed(1) : null}
        />
        <StatCard
          label="Avg. Spread (bps)"
          value={data.avg_spread_bps != null ? data.avg_spread_bps.toFixed(0) : null}
        />
        <StatCard
          label="Inv. Grade %"
          value={data.total_bonds > 0
            ? Math.round((data.investment_grade_count / data.total_bonds) * 100) + "%"
            : null}
        />
      </div>

      <div className="space-y-2">
        <p className="text-xs font-medium text-muted-foreground">Grade Distribution</p>
        {GRADE_ORDER.map((grade) => {
          const count = data.grade_distribution[grade] ?? 0;
          const pct = Math.round((count / total) * 100);
          return (
            <div key={grade} className="flex items-center gap-3">
              <span className="w-32 shrink-0 text-xs text-muted-foreground">{grade}</span>
              <div className="h-2 flex-1 overflow-hidden rounded-full bg-muted/40">
                <div
                  className={`h-full rounded-full ${GRADE_BAR_COLOR[grade]}`}
                  style={{ width: `${pct}%` }}
                />
              </div>
              <span className="w-8 text-right text-xs tabular-nums">{count}</span>
            </div>
          );
        })}
      </div>

      <div className="flex gap-4 text-xs text-muted-foreground">
        <span>
          Investment Grade: <strong className="text-foreground">{data.investment_grade_count}</strong>
        </span>
        <span>
          High Yield: <strong className="text-foreground">{data.high_yield_count}</strong>
        </span>
      </div>
    </div>
  );
}
