"use client";

import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

import {
  UNIVERSE_CONFIG,
  UNIVERSE_KEYS,
  getColumnLabels,
  type PeerCurveResponse,
} from "@/hooks/usePeerCurve";

interface Props {
  data: PeerCurveResponse;
}

const BUCKET_YEARS: Record<string, number> = {
  "<1yr":  0.5,
  "2yr":   2,
  "5yr":   5,
  "10yr":  10,
  "20yr":  20,
  "30yr+": 30,
};

const tooltipStyle: React.CSSProperties = {
  backgroundColor: "hsl(var(--background))",
  border: "1px solid hsl(var(--border))",
  borderRadius: "6px",
  fontSize: "11px",
  color: "hsl(var(--foreground))",
};

export function PeerCurveChart({ data }: Props) {
  const labels = getColumnLabels(data);

  const chartRows = data.chart_data
    .filter((row) => UNIVERSE_KEYS.some((k) => row[k] != null))
    .map((row) => ({ ...row, years: BUCKET_YEARS[row.bucket] ?? 0 }));

  const allValues = data.chart_data
    .flatMap((r) => UNIVERSE_KEYS.map((k) => r[k]))
    .filter((v): v is number => v != null);

  const yMax = allValues.length ? Math.ceil(Math.max(...allValues) / 25) * 25 : 200;

  return (
    <div className="space-y-1.5">
      <h2 className="text-sm font-bold text-orange-400">Average OAS Term Structure</h2>

      <div className="rounded-md border border-border bg-card p-4">
        <ResponsiveContainer width="100%" height={360}>
          <LineChart data={chartRows} margin={{ top: 8, right: 24, left: 0, bottom: 4 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" opacity={0.4} />
            <XAxis
              dataKey="years"
              type="number"
              domain={[0, 32]}
              ticks={[0, 5, 10, 15, 20, 25, 30]}
              tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
              axisLine={false}
              tickLine={false}
              label={{
                value: "Maturity",
                position: "insideBottom",
                offset: -2,
                style: { fontSize: 11, fill: "hsl(var(--muted-foreground))" },
              }}
            />
            <YAxis
              tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
              axisLine={false}
              tickLine={false}
              domain={[0, yMax]}
              label={{
                value: "bps",
                angle: -90,
                position: "insideLeft",
                offset: 12,
                style: { fontSize: 10, fill: "hsl(var(--muted-foreground))" },
              }}
            />
            <Tooltip
              contentStyle={tooltipStyle}
              formatter={(value: number | null, name: string) => [
                value != null ? `${value.toFixed(2)} bps` : "—",
                labels[name as keyof typeof labels] ?? name,
              ]}
              labelFormatter={(years) => `${years}yr`}
            />
            <Legend
              verticalAlign="top"
              wrapperStyle={{ fontSize: 11, paddingBottom: 8 }}
              formatter={(value) => (
                <span style={{ color: UNIVERSE_CONFIG[value as keyof typeof UNIVERSE_CONFIG]?.color }}>
                  {labels[value as keyof typeof labels] ?? value}
                </span>
              )}
            />
            {UNIVERSE_KEYS.map((key) => {
              const cfg = UNIVERSE_CONFIG[key];
              return (
                <Line
                  key={key}
                  type="monotone"
                  dataKey={key}
                  stroke={cfg.color}
                  strokeWidth={key === "issuer" ? 2.5 : 1.5}
                  strokeDasharray={cfg.dashed ? "5 4" : undefined}
                  dot={{ r: key === "issuer" ? 4 : 2.5, fill: cfg.color }}
                  connectNulls={false}
                  activeDot={{ r: 5 }}
                />
              );
            })}
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
