import {
  CartesianGrid,
  Line,
  LineChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

import {
  AXIS_TICK_STYLE,
  chartColors,
  formatBucketLong,
  formatBucketShort,
  type SeriesGranularity,
} from "./theme";
import { ChartTooltip } from "./ChartTooltip";

/**
 * DSO — line chart en ink (pas rubis pour distinguer du chart encaissé).
 * Granularité (mensuelle / hebdo) pilotée par la prop `granularity`.
 * Une ReferenceLine pointillée à 30j sert de repère visuel (norme LME pour
 * le délai de paiement standard B2B).
 */
type DsoTrendChartProps = {
  data: Array<{ bucket: string; dsoDays: number; paidCount: number }>;
  granularity?: SeriesGranularity;
  height?: number;
  /** Référence à afficher en pointillé (30j = LME standard). */
  reference?: number;
};

export function DsoTrendChart({
  data,
  granularity = "month",
  height = 200,
  reference = 30,
}: DsoTrendChartProps) {
  const c = chartColors();

  // On ne plotte pas les buckets sans paiement — sinon la ligne tombe à 0
  // et raconte une histoire fausse. On met null pour avoir un trou visuel
  // (Recharts gère via connectNulls=false).
  const enriched = data.map((d) => ({
    ...d,
    dsoDays: d.paidCount > 0 ? d.dsoDays : null,
  }));
  const xInterval = granularity === "week" ? 1 : 0;

  return (
    <ResponsiveContainer width="100%" height={height}>
      <LineChart data={enriched} margin={{ top: 10, right: 8, left: 8, bottom: 0 }}>
        <CartesianGrid stroke={c.line} strokeDasharray="3 3" vertical={false} />
        <XAxis
          dataKey="bucket"
          tickFormatter={(v) => formatBucketShort(v, granularity)}
          axisLine={false}
          tickLine={false}
          tick={AXIS_TICK_STYLE}
          interval={xInterval}
          dy={6}
        />
        <YAxis
          width={28}
          axisLine={false}
          tickLine={false}
          tick={AXIS_TICK_STYLE}
          tickFormatter={(v) => `${v}j`}
          domain={[0, "dataMax + 5"]}
        />
        <ReferenceLine
          y={reference}
          stroke={c.ink3}
          strokeDasharray="4 4"
          strokeWidth={1}
          label={{
            value: `Norme LME ${reference}j`,
            position: "right",
            fill: c.ink3,
            fontSize: 10,
            fontFamily: "var(--font-sans)",
          }}
        />
        <Tooltip
          content={
            <ChartTooltip
              formatLabel={(v) => formatBucketLong(v, granularity)}
              formatValue={(v, key) =>
                key === "dsoDays" ? `${Math.round(v)} jours` : String(v)
              }
              seriesLabel={{ dsoDays: "DSO moyen" }}
            />
          }
          cursor={{ stroke: c.ink3, strokeWidth: 1, strokeDasharray: "4 4" }}
        />
        <Line
          type="monotone"
          dataKey="dsoDays"
          stroke={c.ink}
          strokeWidth={2}
          dot={{ fill: c.ink, stroke: c.cream, strokeWidth: 2, r: 3 }}
          activeDot={{ r: 5, stroke: c.cream, strokeWidth: 2 }}
          connectNulls={false}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}
