"use client";

import {
  Bar,
  BarChart as ReBarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  Cell,
} from "recharts";

type Props = {
  data: Array<{ label: string; value: number; highlight?: boolean }>;
  height?: number;
  /**
   * Nombre de ticks à sauter entre 2 labels visibles sur l'axe X.
   * 0 = tous les labels, 1 = un sur deux, 3 = un sur quatre…
   */
  xLabelInterval?: number;
  formatY?: (v: number) => string;
  formatTooltipValue?: (v: number) => string;
  /** Resume textuel pour lecteur d'ecran (aria-label). */
  ariaLabel?: string;
  /** Affiche un <details> table des donnees apres le chart. Defaut: true. */
  withDataTable?: boolean;
  /** Libelle de colonne pour la valeur dans la table fallback. Defaut: "Valeur". */
  valueLabel?: string;
};

export function BarChart({
  data,
  height = 280,
  xLabelInterval = 0,
  formatY,
  formatTooltipValue,
  ariaLabel,
  withDataTable = true,
  valueLabel = "Valeur",
}: Props) {
  return (
    <div role="img" aria-label={ariaLabel ?? "Graphique en barres"}>
    <ResponsiveContainer width="100%" height={height}>
      <ReBarChart data={data} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
        <CartesianGrid stroke="rgba(255,255,255,0.05)" vertical={false} />
        <XAxis
          dataKey="label"
          stroke="#52525b"
          tick={{ fill: "#71717a", fontSize: 11 }}
          tickLine={false}
          axisLine={false}
          interval={xLabelInterval}
        />
        <YAxis
          stroke="#52525b"
          tick={{ fill: "#71717a", fontSize: 11 }}
          tickLine={false}
          axisLine={false}
          tickFormatter={formatY}
          width={56}
        />
        <Tooltip
          cursor={{ fill: "rgba(255,255,255,0.04)" }}
          content={({ active, payload, label }) => {
            if (!active || !payload || payload.length === 0) return null;
            const v = payload[0].value as number;
            return (
              <div className="rounded-md border border-border bg-surface-2 px-3 py-2 shadow-xl">
                <div className="text-micro uppercase tracking-wider text-text-faint mb-1">{label}</div>
                <div className="text-xs font-semibold text-text tabular-nums">
                  {formatTooltipValue ? formatTooltipValue(v) : v}
                </div>
              </div>
            );
          }}
        />
        <Bar dataKey="value" radius={[4, 4, 0, 0]}>
          {data.map((d, i) => (
            <Cell key={i} fill={d.highlight ? "#fbbf24" : "#44403c"} />
          ))}
        </Bar>
      </ReBarChart>
    </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 donnees 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">Periode</th>
                <th className="text-right font-medium px-2 py-1 border-b border-border">{valueLabel}</th>
              </tr>
            </thead>
            <tbody className="text-text-muted">
              {data.map((d, idx) => (
                <tr key={idx}>
                  <td className="px-2 py-1 border-b border-border/40">{d.label}</td>
                  <td className="text-right tabular-nums px-2 py-1 border-b border-border/40">
                    {formatTooltipValue ? formatTooltipValue(d.value) : d.value}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </details>
    )}
    </div>
  );
}
