"use client";

import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from "recharts";

export interface DailyAggregate {
  localDate: string;
  avgWait: number | null;
  maxWait: number | null;
  avgFastLane: number | null;
  maxFastLane: number | null;
  uptimePct: number;
  sampleCount: number;
}

interface Props {
  data: DailyAggregate[];
  hasFastLane: boolean;
  mode: "regular" | "fastLane";
}

function shortDay(localDate: string): string {
  // "2026-05-29" → "May 29"
  const [, m, d] = localDate.split("-");
  const month = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][parseInt(m, 10)];
  return `${month} ${parseInt(d, 10)}`;
}

export default function WeeklyStatsChart({ data, hasFastLane, mode }: Props) {
  const showFastLane = mode === "fastLane" && hasFastLane;
  const avgColor = showFastLane ? "#ff4d8d" : "#4ade80";
  const maxColor = showFastLane ? "#ff4d8d" : "#22c55e";
  const maxFill = showFastLane ? "#3d0f22" : "#0a1a0d";
  const chartData = data.map((d) => ({
    day: shortDay(d.localDate),
    avg: showFastLane
      ? (d.avgFastLane !== null ? Math.round(d.avgFastLane) : null)
      : (d.avgWait !== null ? Math.round(d.avgWait) : null),
    max: showFastLane ? d.maxFastLane : d.maxWait,
  }));

  return (
    <div style={{ width: "100%", height: 240 }}>
      <ResponsiveContainer>
        <BarChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 4 }}>
          <CartesianGrid stroke="#272727" strokeDasharray="3 3" vertical={false} />
          <XAxis dataKey="day" stroke="#737373" tick={{ fontSize: 11, fill: "#737373" }} tickLine={false} />
          <YAxis stroke="#737373" tick={{ fontSize: 11, fill: "#737373" }} tickLine={false} axisLine={false} />
          <Tooltip
            cursor={{ fill: "rgba(255,255,255,0.04)" }}
            content={({ active, payload, label }) => {
              if (!active || !payload || payload.length === 0) return null;
              return (
                <div
                  style={{
                    background: "#1c1c1c",
                    border: "1px solid #333",
                    borderRadius: 6,
                    fontSize: "0.75rem",
                    padding: "8px 12px",
                    lineHeight: 1.5,
                  }}
                >
                  <div style={{ color: "#b0b0b0", marginBottom: 2 }}>{label}</div>
                  {payload.map((entry) => {
                    const color = entry.dataKey === "max" ? maxColor : avgColor;
                    const v = entry.value;
                    const display = v === null || v === undefined ? "—" : `${v} min`;
                    return (
                      <div key={String(entry.dataKey)} style={{ color }}>
                        {entry.name} : {display}
                      </div>
                    );
                  })}
                </div>
              );
            }}
          />
          <Legend
            wrapperStyle={{ fontSize: "0.72rem", paddingTop: 4 }}
            formatter={(value) =>
              value === "Max" ? <span style={{ color: maxColor }}>{value}</span> : value
            }
          />
          <Bar name="Avg" dataKey="avg" fill={avgColor} radius={[3, 3, 0, 0]} isAnimationActive={false} />
          <Bar name="Max" dataKey="max" fill={maxFill} stroke={maxColor} strokeWidth={1} radius={[3, 3, 0, 0]} isAnimationActive={false} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}
