"use client";

import { useLocale } from "next-intl";
import * as React from "react";
import { Area, AreaChart, XAxis, YAxis } from "recharts";

import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/components/ui/chart";
import { formatMetricValue, type CwvStatus } from "@/lib/scoring";

export interface CwvSparklinePoint {
  date: string;
  value: number;
}

interface CwvSparklineProps {
  points: CwvSparklinePoint[];
  status: CwvStatus;
  metric: string;
  className?: string;
}

// Map current value status to a CSS color token used both for stroke and gradient fill.
function statusColorVar(status: CwvStatus): string {
  if (status === "good") return "var(--perf-good)";
  if (status === "needs-improvement") return "var(--perf-warning)";
  return "var(--perf-danger)";
}

export function CwvSparkline({ points, status, metric, className }: CwvSparklineProps) {
  // Stable gradient id per render so multiple sparklines on the same page don't collide.
  const reactId = React.useId();
  const gradientId = `cwv-grad-${reactId.replace(/:/g, "")}`;
  const locale = useLocale();
  const dateLocale = locale === "fr" ? "fr-FR" : locale === "es" ? "es-ES" : "en-US";

  const color = statusColorVar(status);

  const config = React.useMemo<ChartConfig>(
    () => ({
      value: {
        label: metric.toUpperCase(),
        color,
      },
    }),
    [color, metric],
  );

  // Empty / single-point states: render a flat placeholder line to keep layout stable.
  if (points.length === 0) {
    return <div className={className ?? "h-20 w-full"} aria-hidden="true" />;
  }

  // Recharts auto-scales the Y domain to the data range, which preserves the
  // existing "relative to observed values" behaviour the user asked for.
  return (
    <ChartContainer config={config} className={className ?? "aspect-auto h-20 w-full"}>
      <AreaChart data={points} margin={{ top: 4, right: 4, left: 4, bottom: 0 }}>
        <defs>
          <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity={0.45} />
            <stop offset="100%" stopColor={color} stopOpacity={0} />
          </linearGradient>
        </defs>
        <XAxis dataKey="date" hide />
        <YAxis hide domain={["dataMin", "dataMax"]} />
        <ChartTooltip
          cursor={{ stroke: "var(--border)", strokeWidth: 1 }}
          content={
            <ChartTooltipContent
              hideIndicator
              labelFormatter={(_, payload) => {
                const raw = payload?.[0]?.payload?.date as string | undefined;
                if (!raw) return "";
                return new Date(raw).toLocaleDateString(dateLocale, {
                  day: "numeric",
                  month: "short",
                  year: "numeric",
                });
              }}
              formatter={(value) => (
                <span className="font-mono font-medium text-foreground tabular-nums">
                  {formatMetricValue(metric, Number(value))}
                </span>
              )}
            />
          }
        />
        <Area
          type="monotone"
          dataKey="value"
          stroke={color}
          strokeWidth={2}
          fill={`url(#${gradientId})`}
          fillOpacity={1}
          isAnimationActive={false}
          activeDot={{ r: 3, stroke: color, strokeWidth: 1, fill: "var(--background)" }}
        />
      </AreaChart>
    </ChartContainer>
  );
}
