"use client";

import {
  CartesianGrid,
  Line,
  LineChart,
  ReferenceArea,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { format } from "date-fns";
import { fr } from "date-fns/locale";

export type ChartPoint = {
  measuredAt: string;
  value: number;
  moment: string;
};

const momentLabel: Record<string, string> = {
  FASTING: "Matin",
  LUNCH: "Midi",
  DINNER: "Soir",
};

function getPointColor(value: number): string {
  if (value < 0.7) return "#f59e0b"; // orange for hypo
  if (value > 1.8) return "#f59e0b"; // orange for hyper
  return "#10b981"; // green for normal
}

function getDotColor(value: number): string {
  return getPointColor(value);
}

export function GlycemiaChart({ data }: { data: ChartPoint[] }) {
  const chartData = data
    .slice()
    .sort((a, b) => new Date(a.measuredAt).getTime() - new Date(b.measuredAt).getTime())
    .map((d) => ({
      ...d,
      ts: new Date(d.measuredAt).getTime(),
      label: format(new Date(d.measuredAt), "d MMM HH:mm", { locale: fr }),
      dotFill: getDotColor(d.value),
    }));

  if (chartData.length === 0) {
    return (
      <div className="flex h-72 items-center justify-center text-sm text-slate-500">
        Pas encore de relevé. Saisissez votre première mesure pour voir la courbe.
      </div>
    );
  }

  const minTs = chartData[0].ts;
  const maxTs = chartData[chartData.length - 1].ts;

  return (
    <div className="h-72 w-full">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={chartData} margin={{ top: 10, right: 16, left: -10, bottom: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
          <XAxis
            dataKey="ts"
            type="number"
            domain={[minTs, maxTs]}
            scale="time"
            tickFormatter={(ts) => format(new Date(ts), "d/MM", { locale: fr })}
            stroke="#64748b"
            fontSize={12}
          />
          <YAxis
            domain={[0.4, 3]}
            tickFormatter={(v) => v.toFixed(1)}
            stroke="#64748b"
            fontSize={12}
            unit=" g/L"
            width={70}
          />
          <ReferenceArea y1={0.7} y2={1.8} fill="#10b981" fillOpacity={0.08} />
          <ReferenceArea y1={0} y2={0.7} fill="#f59e0b" fillOpacity={0.1} />
          <ReferenceArea y1={1.8} y2={5} fill="#f59e0b" fillOpacity={0.08} />
          <Tooltip
            contentStyle={{ borderRadius: 8, border: "1px solid #e2e8f0", fontSize: 13 }}
            labelFormatter={(ts) => format(new Date(ts as number), "EEEE d MMM yyyy 'à' HH:mm", { locale: fr })}
            formatter={(value, _name, item) => {
              const v = typeof value === "number" ? value : Number(value);
              const moment = (item?.payload as { moment?: string } | undefined)?.moment ?? "";
              return [
                `${v.toFixed(2).replace(".", ",")} g/L`,
                momentLabel[moment] ?? moment,
              ];
            }}
          />
          <Line
            type="monotone"
            dataKey="value"
            stroke="#0d9488"
            strokeWidth={2}
            dot={(props) => {
              const { cx, cy, payload } = props;
              if (!payload) return null;
              const color = (payload as any).dotFill || "#0d9488";
              return (
                <circle cx={cx} cy={cy} r={4} fill={color} key={`dot-${(payload as any).ts}`} />
              );
            }}
            activeDot={{ r: 6 }}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}
