"use client";

import {
  Area,
  CartesianGrid,
  ComposedChart,
  Legend,
  Line,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

import { formatChartTick, formatMetricValue, formatTimestamp } from "@/lib/format";

type ChartLine = {
  key: string;
  label: string;
  color: string;
  yAxisId?: string;
};

type ReferenceLineSpec = {
  y: number;
  label?: string;
};

function CrosshairContent({
  active,
  payload,
  label,
}: {
  active?: boolean;
  payload?: Array<{ name: string; value: number; color: string }>;
  label?: string;
}) {
  if (!active || !payload || payload.length === 0) return null;

  return (
    <div
      style={{
        background: "rgba(8, 14, 23, 0.95)",
        border: "1px solid rgba(159, 176, 204, 0.15)",
        borderRadius: 3,
        padding: "6px 10px",
        fontFamily: "var(--font-mono)",
        fontSize: 11,
      }}
    >
      <div style={{ color: "#9fb0cc", marginBottom: 4, fontSize: 10 }}>
        {formatTimestamp(String(label))}
      </div>
      {payload.map((entry) => (
        <div key={entry.name} style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <span style={{ color: entry.color, width: 6, height: 6, borderRadius: "50%", background: entry.color, display: "inline-block", flexShrink: 0 }} />
          <span style={{ color: "#9fb0cc", flex: 1 }}>{entry.name}</span>
          <span style={{ color: "#f5f7fb", fontWeight: 600 }}>
            {typeof entry.value === "number" ? formatMetricValue(entry.value, entry.name) : "—"}
          </span>
        </div>
      ))}
    </div>
  );
}

export function SignalLineChart({
  data,
  lines,
  referenceLines,
  dualAxis,
  height = 440,
  loading,
}: {
  data: Record<string, string | number | null>[];
  lines: ChartLine[];
  referenceLines?: ReferenceLineSpec[];
  dualAxis?: boolean;
  height?: number;
  loading?: boolean;
}) {
  if (data.length === 0) {
    return (
      <div className="chartEmpty">
        {loading ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "center" }}>
            <div style={{ width: "60%", height: 12, background: "rgba(159, 176, 204, 0.08)", borderRadius: 3, animation: "pulse 1.5s ease-in-out infinite" }} />
            <div style={{ width: "40%", height: 12, background: "rgba(159, 176, 204, 0.08)", borderRadius: 3, animation: "pulse 1.5s ease-in-out infinite", animationDelay: "0.3s" }} />
            <p className="eyebrow" style={{ marginTop: 8 }}>Loading chart data...</p>
          </div>
        ) : (
          <p className="eyebrow">No data points available for the selected range.</p>
        )}
      </div>
    );
  }

  const useDualAxis = dualAxis || lines.some((line) => line.yAxisId === "right");
  const primaryLines = useDualAxis
    ? lines.filter((line) => (line.yAxisId ?? "left") === "left")
    : lines;
  const secondaryLines = useDualAxis ? lines.filter((line) => line.yAxisId === "right") : [];

  return (
    <ResponsiveContainer width="100%" height={height}>
      <ComposedChart data={data}>
        <CartesianGrid stroke="rgba(120, 133, 168, 0.10)" strokeDasharray="3 3" />
        <XAxis
          dataKey="ts"
          tick={{ fill: "#6b7d96", fontSize: 11, fontFamily: "var(--font-mono)" }}
          tickFormatter={formatChartTick}
          axisLine={{ stroke: "rgba(159, 176, 204, 0.10)" }}
          tickLine={false}
        />
        <YAxis
          yAxisId="left"
          tick={{ fill: "#6b7d96", fontSize: 11, fontFamily: "var(--font-mono)" }}
          axisLine={false}
          tickLine={false}
        />
        {useDualAxis && (
          <YAxis
            yAxisId="right"
            orientation="right"
            tick={{ fill: "#6b7d96", fontSize: 11, fontFamily: "var(--font-mono)" }}
            axisLine={false}
            tickLine={false}
          />
        )}
        <Tooltip
          content={<CrosshairContent />}
          cursor={{ stroke: "rgba(106, 194, 255, 0.25)", strokeDasharray: "3 3" }}
        />
        <Legend
          wrapperStyle={{ fontSize: 11, fontFamily: "var(--font-mono)" }}
        />
        {referenceLines?.map((ref, i) => (
          <ReferenceLine
            key={i}
            y={ref.y}
            yAxisId="left"
            stroke="rgba(159, 176, 204, 0.25)"
            strokeDasharray="4 4"
            label={ref.label ? { value: ref.label, fill: "#6b7d96", fontSize: 10 } : undefined}
          />
        ))}
        {primaryLines.map((line, i) => (
          <Area
            key={`area-${line.key}`}
            type="monotone"
            dataKey={line.key}
            name={line.label}
            yAxisId={line.yAxisId ?? "left"}
            fill={line.color}
            fillOpacity={i === 0 ? 0.08 : 0}
            stroke="none"
            connectNulls
            legendType="none"
          />
        ))}
        {primaryLines.map((line) => (
          <Line
            key={line.key}
            type="monotone"
            dataKey={line.key}
            name={line.label}
            yAxisId={line.yAxisId ?? "left"}
            dot={false}
            strokeWidth={1.5}
            stroke={line.color}
            connectNulls
          />
        ))}
        {secondaryLines.map((line) => (
          <Line
            key={line.key}
            type="monotone"
            dataKey={line.key}
            name={line.label}
            yAxisId="right"
            dot={false}
            strokeWidth={1.5}
            stroke={line.color}
            strokeDasharray="4 2"
            connectNulls
          />
        ))}
      </ComposedChart>
    </ResponsiveContainer>
  );
}
