"use client";

import {
  Area,
  AreaChart as ReAreaChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

type Series = {
  key: string;
  label: string;
  color?: string;
  axis?: "left" | "right";
};

type Props = {
  data: Array<Record<string, string | number>>;
  xKey: string;
  series: Series[];
  height?: number;
  formatX?: (v: string | number) => string;
  formatY?: (v: number) => string;
  formatYRight?: (v: number) => string;
  formatTooltipValue?: (v: number, key: string) => string;
  /** Resume textuel pour lecteur d'ecran (aria-label sur le wrapper). */
  ariaLabel?: string;
  /** Si true, affiche un <details><summary>Donnees</summary><table>...</table>
   *  comme fallback a11y des donnees du chart. Defaut: true. */
  withDataTable?: boolean;
};

export function AreaChart({
  data,
  xKey,
  series,
  height = 280,
  formatX,
  formatY,
  formatYRight,
  formatTooltipValue,
  ariaLabel,
  withDataTable = true,
}: Props) {
  const hasRightAxis = series.some((s) => s.axis === "right");

  return (
    <div role="img" aria-label={ariaLabel ?? `Graphique : ${series.map((s) => s.label).join(", ")}`}>
    <ResponsiveContainer width="100%" height={height}>
      <ReAreaChart data={data} margin={{ top: 8, right: hasRightAxis ? 8 : 8, left: -12, bottom: 0 }}>
        <defs>
          {series.map((s, i) => {
            const color = s.color ?? (i === 0 ? "#fbbf24" : "#a78bfa");
            return (
              <linearGradient key={s.key} id={`grad-${s.key}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={color} stopOpacity={0.35} />
                <stop offset="100%" stopColor={color} stopOpacity={0} />
              </linearGradient>
            );
          })}
        </defs>
        <CartesianGrid stroke="rgba(255,255,255,0.05)" vertical={false} />
        <XAxis
          dataKey={xKey}
          stroke="#52525b"
          tick={{ fill: "#71717a", fontSize: 11 }}
          tickLine={false}
          axisLine={false}
          tickFormatter={formatX}
          minTickGap={24}
        />
        <YAxis
          yAxisId="left"
          stroke="#52525b"
          tick={{ fill: "#71717a", fontSize: 11 }}
          tickLine={false}
          axisLine={false}
          tickFormatter={formatY}
          width={48}
        />
        {hasRightAxis && (
          <YAxis
            yAxisId="right"
            orientation="right"
            stroke="#52525b"
            tick={{ fill: "#71717a", fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            tickFormatter={formatYRight ?? formatY}
            width={56}
          />
        )}
        <Tooltip
          cursor={{ stroke: "rgba(255,255,255,0.12)", strokeWidth: 1 }}
          content={({ active, payload, label }) => {
            if (!active || !payload || payload.length === 0) return null;
            return (
              <div className="rounded-md border border-border bg-surface-2 px-3 py-2 shadow-xl min-w-[180px]">
                <div className="text-micro uppercase tracking-wider text-text-faint mb-1.5">
                  {formatX ? formatX(label as string) : (label as string)}
                </div>
                {payload.map((p) => {
                  const s = series.find((x) => x.key === p.dataKey);
                  if (!s) return null;
                  const color = s.color ?? "#fbbf24";
                  const v = p.value as number;
                  return (
                    <div key={s.key} className="flex items-center gap-2 text-xs py-0.5">
                      <span className="size-2 rounded-full" style={{ backgroundColor: color }} />
                      <span className="text-text-muted">{s.label}</span>
                      <span className="ml-auto font-semibold text-text tabular-nums">
                        {formatTooltipValue ? formatTooltipValue(v, s.key) : v}
                      </span>
                    </div>
                  );
                })}
              </div>
            );
          }}
        />
        {series.map((s, i) => {
          const color = s.color ?? (i === 0 ? "#fbbf24" : "#a78bfa");
          return (
            <Area
              key={s.key}
              yAxisId={s.axis ?? "left"}
              type="monotone"
              dataKey={s.key}
              stroke={color}
              strokeWidth={2}
              fill={`url(#grad-${s.key})`}
              activeDot={{ r: 4, strokeWidth: 0 }}
            />
          );
        })}
      </ReAreaChart>
    </ResponsiveContainer>
    {withDataTable && data.length > 0 && (
      <details className="mt-2 text-xs text-text-dim">
        <summary className="cursor-pointer hover:text-text-muted transition-colors">
          Voir les données du graphique (tableau)
        </summary>
        <div className="mt-2 overflow-x-auto">
          <table className="w-full text-xs">
            <thead className="text-text-faint">
              <tr>
                <th className="text-left font-medium px-2 py-1 border-b border-border">{xKey}</th>
                {series.map((s) => (
                  <th key={s.key} className="text-right font-medium px-2 py-1 border-b border-border">
                    {s.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="text-text-muted">
              {data.map((row, idx) => (
                <tr key={idx}>
                  <td className="px-2 py-1 border-b border-border/40">
                    {formatX ? formatX(row[xKey]) : String(row[xKey])}
                  </td>
                  {series.map((s) => (
                    <td key={s.key} className="text-right tabular-nums px-2 py-1 border-b border-border/40">
                      {formatTooltipValue
                        ? formatTooltipValue(Number(row[s.key]), s.key)
                        : String(row[s.key])}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </details>
    )}
    </div>
  );
}
