import {
  ResponsiveContainer,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ScatterChart,
  Scatter,
  ComposedChart,
} from "recharts";
import curves from "@/data/model_curves.json";
import experimental from "@/data/experimental_data.json";
import kinetics from "@/data/kinetic_parameters.json";

const TONE_HEX: Record<string, string> = {
  emerald: "oklch(0.74 0.16 158)",
  teal: "oklch(0.74 0.12 188)",
  cyan: "oklch(0.78 0.11 210)",
  amber: "oklch(0.82 0.14 80)",
};

const GRID = "oklch(0.4 0.025 252 / 40%)";
const AXIS = "oklch(0.72 0.02 250)";

function TT({ active, payload, label }: any) {
  if (!active || !payload || !payload.length) return null;
  return (
    <div className="rounded-lg border border-border bg-background/95 p-2 text-[11px] shadow-lg backdrop-blur">
      <div className="mb-1 text-muted-foreground">C₀ ≈ {label} ppmv</div>
      {payload.map((p: any, i: number) => (
        <div key={i} className="flex items-center gap-2">
          <span
            className="inline-block h-2 w-2 rounded-full"
            style={{ background: p.color }}
          />
          <span className="text-foreground">
            {p.name}: {typeof p.value === "number" ? p.value.toFixed(2) : p.value}%
          </span>
        </div>
      ))}
      <div className="mt-1 text-[10px] text-muted-foreground">
        {payload.some((p: any) => p.name?.startsWith("Obs"))
          ? "Experimental observation"
          : "Reconstructed model curve"}
      </div>
    </div>
  );
}

export function HeroSnapshotChart() {
  return (
    <div className="h-48 w-full min-w-0">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={curves.points} margin={{ top: 6, right: 12, left: -8, bottom: 4 }}>
          <CartesianGrid stroke={GRID} strokeDasharray="3 4" vertical={false} />
          <XAxis
            dataKey="c0_ppmv"
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "C₀ (ppmv)", position: "insideBottom", offset: -2, fill: AXIS, fontSize: 10 }}
          />
          <YAxis
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "X (%)", angle: -90, position: "insideLeft", fill: AXIS, fontSize: 10 }}
          />
          <Tooltip content={<TT />} />
          {kinetics.map((k) => (
            <Line
              key={k.pollutant}
              dataKey={k.series_key}
              name={k.pollutant}
              type="monotone"
              stroke={TONE_HEX[k.tone]}
              strokeWidth={1.6}
              dot={false}
            />
          ))}
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

export function KineticFitChart({
  pollutant,
  seriesKey,
  tone,
}: {
  pollutant: string;
  seriesKey: string;
  tone: string;
}) {
  const obs = experimental
    .filter((r) => r.pollutant === pollutant)
    .map((r) => ({ c0: r.c0_ppmv, X: r.conversion_pct, phase: r.phase, sd: r.conversion_sd_pct }));
  const curve = curves.points.map((p: any) => ({
    c0: p.c0_ppmv,
    Xmodel: p[seriesKey],
  }));
  const merged = [
    ...curve.map((c) => ({ c0: c.c0, Xmodel: c.Xmodel })),
    ...obs.map((o) => ({ c0: o.c0, Xobs: o.X })),
  ].sort((a, b) => a.c0 - b.c0);
  return (
    <div className="h-56 w-full min-w-0">
      <ResponsiveContainer width="100%" height="100%">
        <ComposedChart data={merged} margin={{ top: 6, right: 12, left: -6, bottom: 4 }}>
          <CartesianGrid stroke={GRID} strokeDasharray="3 4" vertical={false} />
          <XAxis
            dataKey="c0"
            type="number"
            domain={[0, "dataMax"]}
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "C₀ (ppmv)", position: "insideBottom", offset: -2, fill: AXIS, fontSize: 10 }}
          />
          <YAxis
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "X (%)", angle: -90, position: "insideLeft", fill: AXIS, fontSize: 10 }}
          />
          <Tooltip content={<TT />} />
          <Line
            dataKey="Xmodel"
            name="Model"
            type="monotone"
            stroke={TONE_HEX[tone]}
            strokeWidth={1.6}
            dot={false}
            connectNulls
          />
          <Scatter
            dataKey="Xobs"
            name="Obs"
            fill={TONE_HEX[tone]}
            shape="circle"
          />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}

export function ComparativeCurveChart() {
  return (
    <div className="h-80 w-full min-w-0">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={curves.points} margin={{ top: 8, right: 20, left: 0, bottom: 8 }}>
          <CartesianGrid stroke={GRID} strokeDasharray="3 4" vertical={false} />
          <XAxis
            dataKey="c0_ppmv"
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "C₀ (ppmv)", position: "insideBottom", offset: -2, fill: AXIS, fontSize: 10 }}
          />
          <YAxis
            tick={{ fill: AXIS, fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{ value: "Conversion X (%)", angle: -90, position: "insideLeft", fill: AXIS, fontSize: 10 }}
          />
          <Tooltip content={<TT />} />
          <Legend wrapperStyle={{ fontSize: 11, color: AXIS }} />
          {kinetics.map((k) => (
            <Line
              key={k.pollutant}
              dataKey={k.series_key}
              name={k.pollutant}
              type="monotone"
              stroke={TONE_HEX[k.tone]}
              strokeWidth={1.8}
              dot={false}
            />
          ))}
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

export { TONE_HEX };
