"use client";

import { useEffect, useRef, useState } from "react";
import {
  CalendarDays,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { ChartPanel, type ChartSeries } from "@/components/shared/chart";
import { Panel } from "@/components/shared/page";
import type {
  AnalyticsPeriod,
  SessionActiveUsersReport,
  SessionCostReport,
  SessionMeanChargingReport,
  SessionNewUsersReport,
  SessionRevenueReport,
  SessionReturningUsersReport,
} from "./session-analytics-contract";

type ChartMetric =
  | "revenue-profit"
  | "energy-bill"
  | "cost"
  | "active-users"
  | "new-users"
  | "returning-users"
  | "mean-charging";
type ReportKind =
  | "revenue"
  | "cost"
  | "active-users"
  | "new-users"
  | "returning-users"
  | "mean-charging";
type ChartReportData =
  | SessionRevenueReport
  | SessionCostReport
  | SessionActiveUsersReport
  | SessionNewUsersReport
  | SessionReturningUsersReport
  | SessionMeanChargingReport;
type DateRange = {
  startDate: string;
  endDate: string;
  displayEndDate?: string;
};
type WeekOption = DateRange & { label: string };

const PERIODS: readonly { value: AnalyticsPeriod; label: string }[] = [
  { value: "daily", label: "Daily" },
  { value: "weekly", label: "Weekly" },
  { value: "monthly", label: "Monthly" },
  { value: "yearly", label: "Yearly" },
];
const MONTHS = Array.from({ length: 12 }, (_, index) => ({
  value: String(index + 1).padStart(2, "0"),
  label: new Intl.DateTimeFormat("en-US", {
    month: "long",
    timeZone: "UTC",
  }).format(new Date(Date.UTC(2020, index, 1))),
}));
const FIRST_ANALYTICS_YEAR = 2020;

function dateFromString(value: string) {
  return new Date(value + "T00:00:00.000Z");
}

function dateString(value: Date) {
  return value.toISOString().slice(0, 10);
}

function shiftDays(value: string, days: number) {
  const date = dateFromString(value);
  date.setUTCDate(date.getUTCDate() + days);
  return dateString(date);
}

function daysInMonth(year: number, month: number) {
  return new Date(Date.UTC(year, month, 0)).getUTCDate();
}

function clampDate(value: string, maxDate: string) {
  return value > maxDate ? maxDate : value;
}

function withMonthAndDay(year: number, month: number, day: number) {
  const monthText = String(month).padStart(2, "0");
  const dayText = String(Math.min(day, daysInMonth(year, month))).padStart(2, "0");
  return year + "-" + monthText + "-" + dayText;
}

function moveMonth(value: string, delta: number) {
  const date = dateFromString(value);
  const wantedDay = date.getUTCDate();
  date.setUTCDate(1);
  date.setUTCMonth(date.getUTCMonth() + delta);
  return withMonthAndDay(
    date.getUTCFullYear(),
    date.getUTCMonth() + 1,
    wantedDay,
  );
}

function monthRange(anchorDate: string, today: string): DateRange {
  const year = Number(anchorDate.slice(0, 4));
  const month = Number(anchorDate.slice(5, 7));
  const monthText = String(month).padStart(2, "0");
  return {
    startDate: year + "-" + monthText + "-01",
    endDate: clampDate(
      year + "-" + monthText + "-" + daysInMonth(year, month),
      today,
    ),
  };
}

function rangeForView(
  view: AnalyticsPeriod,
  anchorDate: string,
  dailyRange: DateRange,
  today: string,
): DateRange {
  if (view === "daily") return dailyRange;
  if (view === "weekly") return monthRange(anchorDate, today);

  const year = Number(anchorDate.slice(0, 4));
  if (view === "monthly") {
    return {
      startDate: year + "-01-01",
      endDate: clampDate(year + "-12-31", today),
    };
  }

  const firstYear = year - 6;
  return {
    startDate: firstYear + "-01-01",
    endDate: clampDate(year + "-12-31", today),
  };
}

function formatShortDate(value: string) {
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
    timeZone: "UTC",
  }).format(dateFromString(value));
}

function formatRange(range: DateRange) {
  return formatShortDate(range.startDate) + " – " + formatShortDate(range.endDate);
}

function formatWeeklyCategory(value: string, anchorDate: string) {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;

  const monthStart = anchorDate.slice(0, 7) + "-01";
  const firstWeekStart = shiftDays(
    monthStart,
    -((dateFromString(monthStart).getUTCDay() + 6) % 7),
  );
  const weekStart = shiftDays(
    value,
    -((dateFromString(value).getUTCDay() + 6) % 7),
  );
  const weekNumber =
    Math.floor(
      (dateFromString(weekStart).getTime() -
        dateFromString(firstWeekStart).getTime()) /
        (7 * 24 * 60 * 60 * 1000),
    ) + 1;

  return [
    `Week ${weekNumber}`,
    `${formatShortDate(weekStart)} – ${formatShortDate(shiftDays(weekStart, 6))}`,
  ];
}

function formatMonthlyCategory(value: string) {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    timeZone: "UTC",
  }).format(dateFromString(value));
}

function formatYearlyCategory(value: string) {
  const match = /^(\d{4})-\d{2}-\d{2}$/.exec(value);
  return match?.[1] ?? value;
}

function formatMainPeriod(
  view: AnalyticsPeriod,
  anchorDate: string,
  range: DateRange,
) {
  const year = Number(anchorDate.slice(0, 4));
  if (view === "daily") return formatRange(range);
  if (view === "weekly") {
    return new Intl.DateTimeFormat("en-US", {
      month: "long",
      year: "numeric",
      timeZone: "UTC",
    }).format(dateFromString(anchorDate.slice(0, 7) + "-01"));
  }
  if (view === "monthly") return String(year);
  return year - 6 + " – " + year;
}

function weekOptionsForMonth(
  anchorDate: string,
  today: string,
  selectedRange: DateRange,
): WeekOption[] {
  const year = Number(anchorDate.slice(0, 4));
  const month = Number(anchorDate.slice(5, 7));
  const monthText = String(month).padStart(2, "0");
  const monthStart = year + "-" + monthText + "-01";
  const monthEnd =
    year + "-" + monthText + "-" + daysInMonth(year, month);
  const firstDate = dateFromString(monthStart);
  const daysSinceMonday = (firstDate.getUTCDay() + 6) % 7;
  let weekStart = shiftDays(monthStart, -daysSinceMonday);
  const options: WeekOption[] = [];

  while (weekStart <= monthEnd) {
    const weekEnd = shiftDays(weekStart, 6);
    const cappedEnd = clampDate(weekEnd, today);
    if (weekStart <= today && cappedEnd >= weekStart) {
      options.push({
        startDate: weekStart,
        endDate: cappedEnd,
        displayEndDate: weekEnd,
        label: formatRange({ startDate: weekStart, endDate: weekEnd }),
      });
    }
    weekStart = shiftDays(weekStart, 7);
  }

  if (
    !options.some(
      (option) =>
        option.startDate === selectedRange.startDate &&
        option.endDate === selectedRange.endDate,
    )
  ) {
    options.push({ ...selectedRange, label: formatRange(selectedRange) });
  }
  return options.sort((left, right) =>
    right.startDate.localeCompare(left.startDate),
  );
}

function yearOptions(today: string) {
  const currentYear = Number(today.slice(0, 4));
  return Array.from(
    { length: currentYear - FIRST_ANALYTICS_YEAR + 1 },
    (_, index) => currentYear - index,
  );
}

function getReportKind(metric: ChartMetric): ReportKind {
  if (metric === "revenue-profit" || metric === "energy-bill") return "revenue";
  if (metric === "cost") return "cost";
  if (metric === "active-users") return "active-users";
  return metric;
}

const RETURNING_USER_SERIES = [
  { key: "veryLowCount", name: "Very Low" },
  { key: "lowCount", name: "Low" },
  { key: "mediumCount", name: "Medium" },
  { key: "highCount", name: "High" },
  { key: "veryHighCount", name: "Very High" },
] as const;

function bucketForView(date: string, view: AnalyticsPeriod) {
  if (view === "weekly") {
    const utcDate = dateFromString(date);
    return shiftDays(date, -((utcDate.getUTCDay() + 6) % 7));
  }
  if (view === "monthly") return date.slice(0, 7) + "-01";
  if (view === "yearly") return date.slice(0, 4) + "-01-01";
  return date;
}

function bucketStartsForRange(range: DateRange, view: AnalyticsPeriod) {
  const starts: string[] = [];
  let date = bucketForView(range.startDate, view);
  while (date <= range.endDate) {
    starts.push(date);
    if (view === "daily") {
      date = shiftDays(date, 1);
    } else if (view === "weekly") {
      date = shiftDays(date, 7);
    } else if (view === "monthly") {
      const nextMonth = dateFromString(date);
      nextMonth.setUTCMonth(nextMonth.getUTCMonth() + 1);
      date = dateString(nextMonth);
    } else {
      date = `${Number(date.slice(0, 4)) + 1}-01-01`;
    }
  }
  return starts;
}

function chartData(
  metric: ChartMetric,
  data: ChartReportData,
  view: AnalyticsPeriod,
  range: DateRange,
): { categories: string[]; series: ChartSeries } {
  if (metric === "revenue-profit" || metric === "energy-bill") {
    const report = data as SessionRevenueReport;
    const rows = [...report.summary].sort((left, right) =>
      left.date.localeCompare(right.date),
    );
    return {
      categories: rows.map((row) => row.date),
      series:
        metric === "revenue-profit"
          ? [
              { name: "Revenue", data: rows.map((row) => row.revenue) },
              { name: "Profit", data: rows.map((row) => row.profit) },
            ]
          : [{ name: "Energy Bill", data: rows.map((row) => row.energyBill) }],
    };
  }

  if (metric === "cost") {
    const report = data as SessionCostReport;
    const rows = [...report.summary].sort((left, right) =>
      left.date.localeCompare(right.date),
    );
    return {
      categories: rows.map((row) => row.date),
      series: [
        { name: "Energy Cost", data: rows.map((row) => row.energyCost) },
        { name: "Time Cost", data: rows.map((row) => row.timeCost) },
        { name: "Idle Cost", data: rows.map((row) => row.idleCost) },
      ],
    };
  }

  if (metric === "returning-users") {
    const report = data as SessionReturningUsersReport;
    const byDate = new Map(report.summary.map((row) => [row.date, row] as const));
    const dailyRows: SessionReturningUsersReport["summary"] = [];
    for (
      let date = range.startDate;
      date <= range.endDate;
      date = shiftDays(date, 1)
    ) {
      dailyRows.push(
        byDate.get(date) ?? {
          date,
          veryLowCount: 0,
          lowCount: 0,
          mediumCount: 0,
          highCount: 0,
          veryHighCount: 0,
        },
      );
    }

    if (view === "daily") {
      return {
        categories: dailyRows.map((row) => row.date),
        series: RETURNING_USER_SERIES.map(({ key, name }) => ({
          name,
          data: dailyRows.map((row) => row[key]),
        })),
      };
    }

    type ReturningTotals = Omit<SessionReturningUsersReport["summary"][number], "date">;
    const groups = new Map<string, ReturningTotals>();
    for (const row of dailyRows) {
      const bucket = bucketForView(row.date, view);
      const group = groups.get(bucket) ?? {
        veryLowCount: 0,
        lowCount: 0,
        mediumCount: 0,
        highCount: 0,
        veryHighCount: 0,
      };
      for (const { key } of RETURNING_USER_SERIES) group[key] += row[key];
      groups.set(bucket, group);
    }
    const entries = [...groups.entries()].sort(([left], [right]) =>
      left.localeCompare(right),
    );
    return {
      categories: entries.map(([date]) => date),
      series: RETURNING_USER_SERIES.map(({ key, name }) => ({
        name,
        data: entries.map(([, group]) => group[key]),
      })),
    };
  }

  if (metric === "mean-charging") {
    const report = data as SessionMeanChargingReport;
    const byDate = new Map(report.summary.map((row) => [row.date, row] as const));
    const dailyRows: SessionMeanChargingReport["summary"] = [];
    for (
      let date = range.startDate;
      date <= range.endDate;
      date = shiftDays(date, 1)
    ) {
      dailyRows.push(
        byDate.get(date) ?? {
          date,
          meanChargingDurationAcCharger: 0,
          meanChargingDurationDcCharger: 0,
        },
      );
    }

    if (view === "daily") {
      return {
        categories: dailyRows.map((row) => row.date),
        series: [
          {
            name: "AC Charger",
            data: dailyRows.map((row) => row.meanChargingDurationAcCharger),
          },
          {
            name: "DC Charger",
            data: dailyRows.map((row) => row.meanChargingDurationDcCharger),
          },
        ],
      };
    }

    const groups = new Map<
      string,
      { acTotal: number; acDays: number; dcTotal: number; dcDays: number }
    >();
    for (const row of dailyRows) {
      const bucket = bucketForView(row.date, view);
      const group = groups.get(bucket) ?? {
        acTotal: 0,
        acDays: 0,
        dcTotal: 0,
        dcDays: 0,
      };
      if (row.meanChargingDurationAcCharger > 0) {
        group.acTotal += row.meanChargingDurationAcCharger;
        group.acDays += 1;
      }
      if (row.meanChargingDurationDcCharger > 0) {
        group.dcTotal += row.meanChargingDurationDcCharger;
        group.dcDays += 1;
      }
      groups.set(bucket, group);
    }
    const entries = [...groups.entries()].sort(([left], [right]) =>
      left.localeCompare(right),
    );
    return {
      categories: entries.map(([date]) => date),
      series: [
        {
          name: "AC Charger (avg. daily mean)",
          data: entries.map(([, group]) =>
            group.acDays ? group.acTotal / group.acDays : 0,
          ),
        },
        {
          name: "DC Charger (avg. daily mean)",
          data: entries.map(([, group]) =>
            group.dcDays ? group.dcTotal / group.dcDays : 0,
          ),
        },
      ],
    };
  }

  if (metric === "new-users") {
    const report = data as SessionNewUsersReport;
    const countsByBucket = new Map<string, number>();
    for (const row of report.summary) {
      const bucket = bucketForView(row.date, view);
      countsByBucket.set(
        bucket,
        (countsByBucket.get(bucket) ?? 0) + row.count,
      );
    }
    const categories = bucketStartsForRange(range, view);
    return {
      categories,
      series: [
        {
          name: "New Users",
          data: categories.map((category) => countsByBucket.get(category) ?? 0),
        },
      ],
    };
  }

  const report = data as SessionActiveUsersReport;
  const counts = new Map(
    report.summary.map((row) => [row.date, row.activeUsers] as const),
  );
  const dailyRows: Array<{ date: string; activeUsers: number }> = [];
  for (
    let date = range.startDate;
    date <= range.endDate;
    date = shiftDays(date, 1)
  ) {
    dailyRows.push({ date, activeUsers: counts.get(date) ?? 0 });
  }
  if (view === "daily") {
    return {
      categories: dailyRows.map((row) => row.date),
      series: [
        { name: "Active Users", data: dailyRows.map((row) => row.activeUsers) },
      ],
    };
  }

  const groups = new Map<string, { total: number; count: number }>();
  for (const row of dailyRows) {
    const bucket = bucketForView(row.date, view);
    const group = groups.get(bucket) ?? { total: 0, count: 0 };
    group.total += row.activeUsers;
    group.count += 1;
    groups.set(bucket, group);
  }
  const entries = [...groups.entries()].sort(([left], [right]) =>
    left.localeCompare(right),
  );
  return {
    categories: entries.map(([date]) => date),
    series: [
      {
        name: "Average Daily Active Users",
        data: entries.map(([, group]) => group.total / group.count),
      },
    ],
  };
}

function PeriodSelect({
  label,
  value,
  options,
  onChange,
}: {
  label: string;
  value: string;
  options: Array<{ value: string; label: string }>;
  onChange: (value: string) => void;
}) {
  return (
    <label className="block text-sm">
      <span className="mb-1 block text-xs font-medium text-muted-foreground">
        {label}
      </span>
      <select
        className="form-input h-7 w-full text-xs"
        value={value}
        onChange={(event) => onChange(event.target.value)}
      >
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </label>
  );
}

function PeriodControls({
  view,
  onViewChange,
  anchorDate,
  onAnchorDateChange,
  range,
  dailyRange,
  onDailyRangeChange,
  today,
}: {
  view: AnalyticsPeriod;
  onViewChange: (view: AnalyticsPeriod) => void;
  anchorDate: string;
  onAnchorDateChange: (date: string) => void;
  range: DateRange;
  dailyRange: DateRange;
  onDailyRangeChange: (range: DateRange) => void;
  today: string;
}) {
  const [pickerOpen, setPickerOpen] = useState(false);
  const [year = 2020, month = 1, day = 1] = anchorDate
    .split("-")
    .map(Number);
  const years = yearOptions(today);
  const weekOptions = weekOptionsForMonth(anchorDate, today, dailyRange);
  const currentMonth = Number(today.slice(5, 7));
  const currentYear = Number(today.slice(0, 4));
  const selectableMonths = MONTHS.filter(
    (option) => year < currentYear || Number(option.value) <= currentMonth,
  );
  const displayedRange =
    view === "daily" && dailyRange.displayEndDate
      ? { startDate: dailyRange.startDate, endDate: dailyRange.displayEndDate }
      : range;
  const label = formatMainPeriod(view, anchorDate, displayedRange);

  function updateDailyAnchor(date: string) {
    const safeEnd = clampDate(date, today);
    onAnchorDateChange(safeEnd);
    onDailyRangeChange({
      startDate: shiftDays(safeEnd, -6),
      endDate: safeEnd,
    });
  }

  function previousPeriod() {
    if (view === "daily") {
      const displayEndDate = dailyRange.displayEndDate
        ? shiftDays(dailyRange.displayEndDate, -7)
        : undefined;
      const endDate =
        displayEndDate ?? shiftDays(dailyRange.endDate, -7);
      onDailyRangeChange({
        startDate: shiftDays(dailyRange.startDate, -7),
        endDate,
        displayEndDate,
      });
      onAnchorDateChange(endDate);
    } else if (view === "weekly") {
      onAnchorDateChange(moveMonth(anchorDate, -1));
    } else if (view === "monthly") {
      onAnchorDateChange(
        withMonthAndDay(year - 1, month, day),
      );
    } else {
      onAnchorDateChange((year - 1) + "-12-31");
    }
  }

  function nextPeriod() {
    if (view === "daily") {
      const startDate = shiftDays(dailyRange.startDate, 7);
      const displayEndDate = dailyRange.displayEndDate
        ? shiftDays(dailyRange.displayEndDate, 7)
        : undefined;
      const endDate = clampDate(
        displayEndDate ?? shiftDays(dailyRange.endDate, 7),
        today,
      );
      onDailyRangeChange({ startDate, endDate, displayEndDate });
      onAnchorDateChange(endDate);
    } else if (view === "weekly") {
      onAnchorDateChange(moveMonth(anchorDate, 1));
    } else if (view === "monthly") {
      onAnchorDateChange(withMonthAndDay(year + 1, month, day));
    } else {
      onAnchorDateChange((year + 1) + "-12-31");
    }
  }

  const previousDisabled =
    (view === "daily" && dailyRange.startDate <= FIRST_ANALYTICS_YEAR + "-01-01") ||
    (view === "weekly" && anchorDate.slice(0, 7) <= FIRST_ANALYTICS_YEAR + "-01") ||
    (view === "monthly" && year <= FIRST_ANALYTICS_YEAR) ||
    (view === "yearly" && year <= FIRST_ANALYTICS_YEAR + 6);
  const nextDisabled =
    (view === "daily" && dailyRange.endDate >= today) ||
    (view === "weekly" && year === currentYear && month >= currentMonth) ||
    (view === "monthly" && year >= currentYear) ||
    (view === "yearly" && year >= currentYear);

  function selectYear(value: string) {
    const selectedYear = Number(value);
    if (view === "yearly") {
      onAnchorDateChange(selectedYear + "-12-31");
    } else if (view === "monthly") {
      onAnchorDateChange(selectedYear + "-01-01");
    } else {
      updateDailyAnchor(
        clampDate(withMonthAndDay(selectedYear, month, day), today),
      );
    }
  }

  function selectMonth(value: string) {
    const selectedMonth = Number(value);
    if (view === "weekly") {
      onAnchorDateChange(year + "-" + value + "-01");
    } else {
      updateDailyAnchor(
        clampDate(withMonthAndDay(year, selectedMonth, day), today),
      );
    }
  }

  return (
    <div className="flex flex-row flex-wrap items-end justify-end gap-4">
      <div className="flex flex-col items-center gap-1">
        <span className="text-xs font-medium text-muted-foreground">View</span>
        <div className="flex max-w-full gap-0.5 overflow-x-auto rounded-lg bg-muted p-0.5">
          {PERIODS.map((period) => (
            <button
              key={period.value}
              type="button"
              aria-pressed={view === period.value}
              className={
                "whitespace-nowrap rounded-md px-2.5 py-1.5 text-xs font-semibold transition-colors " +
                (view === period.value
                  ? "bg-card text-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground")
              }
              onClick={() => {
                onViewChange(period.value);
                setPickerOpen(false);
              }}
            >
              {period.label}
            </button>
          ))}
        </div>
      </div>

      <div className="relative flex flex-col items-center gap-1">
        <span className="text-xs font-medium text-muted-foreground">Period</span>
        <div className="flex items-center">
          <Button
            type="button"
            variant="outline"
            size="icon"
            className="h-9 w-9 shrink-0 rounded-l-xl rounded-r-none"
            disabled={previousDisabled}
            aria-label="Previous period"
            onClick={previousPeriod}
          >
            <ChevronLeft className="size-4" aria-hidden="true" />
          </Button>
          <Button
            type="button"
            variant="outline"
            aria-expanded={pickerOpen}
            aria-haspopup="dialog"
            className="-ml-px h-9 min-w-0 w-[160px] justify-start gap-1.5 rounded-none px-2 text-xs font-semibold"
            onClick={() => setPickerOpen((open) => !open)}
          >
            <CalendarDays
              className="size-4 shrink-0 text-muted-foreground"
              aria-hidden="true"
            />
            <span className="min-w-0 flex-1 truncate text-left">{label}</span>
            {pickerOpen ? (
              <ChevronUp className="size-3 shrink-0" aria-hidden="true" />
            ) : (
              <ChevronDown className="size-3 shrink-0" aria-hidden="true" />
            )}
          </Button>
          <Button
            type="button"
            variant="outline"
            size="icon"
            className="-ml-px h-9 w-9 shrink-0 rounded-l-none rounded-r-xl"
            disabled={nextDisabled}
            aria-label="Next period"
            onClick={nextPeriod}
          >
            <ChevronRight className="size-4" aria-hidden="true" />
          </Button>
        </div>
        {pickerOpen && (
          <div
            role="dialog"
            aria-label="Select period"
            className="absolute left-1/2 top-full z-50 mt-2 w-[min(240px,90vw)] -translate-x-1/2 rounded-xl border border-border bg-card p-2.5 shadow-xl"
          >
            <h3 className="mb-1.5 text-xs font-semibold">Select period</h3>
            <div className="space-y-1.5">
              {view === "daily" && (
                <PeriodSelect
                  label="Week"
                  value={dailyRange.startDate}
                  options={weekOptions.map((option) => ({
                    value: option.startDate,
                    label: option.label,
                  }))}
                  onChange={(value) => {
                    const selected = weekOptions.find(
                      (option) => option.startDate === value,
                    );
                    if (selected) {
                      onDailyRangeChange(selected);
                      onAnchorDateChange(selected.endDate);
                    }
                  }}
                />
              )}
              {(view === "daily" || view === "weekly") && (
                <PeriodSelect
                  label="Month"
                  value={String(month).padStart(2, "0")}
                  options={selectableMonths}
                  onChange={selectMonth}
                />
              )}
              {(view === "daily" || view === "weekly" || view === "monthly") && (
                <PeriodSelect
                  label="Year"
                  value={String(year)}
                  options={years.map((option) => ({
                    value: String(option),
                    label: String(option),
                  }))}
                  onChange={selectYear}
                />
              )}
              {view === "yearly" && (
                <PeriodSelect
                  label="Through"
                  value={String(year)}
                  options={years.map((option) => ({
                    value: String(option),
                    label: String(option),
                  }))}
                  onChange={selectYear}
                />
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export function SessionAnalyticsChart({
  metric,
  title,
  initialData,
  startDate,
  endDate,
  today,
}: {
  metric: ChartMetric;
  title: string;
  initialData: ChartReportData;
  startDate: string;
  endDate: string;
  today: string;
}) {
  const report = getReportKind(metric);
  const [view, setView] = useState<AnalyticsPeriod>(
    metric === "new-users" ? "monthly" : "daily",
  );
  const [anchorDate, setAnchorDate] = useState(endDate);
  const [dailyRange, setDailyRange] = useState<DateRange>(
    metric === "new-users"
      ? { startDate: shiftDays(endDate, -6), endDate }
      : { startDate, endDate },
  );
  const [data, setData] = useState<ChartReportData>(initialData);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const range = rangeForView(view, anchorDate, dailyRange, today);
  const requestKey = view + ":" + range.startDate + ":" + range.endDate;
  const lastRequestKey = useRef(requestKey);
  const chart = chartData(metric, data, view, range);
  const categoryLabelFormatter =
    view === "weekly"
      ? (value: string) => formatWeeklyCategory(value, anchorDate)
      : view === "monthly"
        ? formatMonthlyCategory
        : view === "yearly"
          ? formatYearlyCategory
          : undefined;
  const newUserCounts = chart.series[0]?.data ?? [];
  const newUserTotal = newUserCounts.reduce((sum, count) => sum + count, 0);
  const activePeriods = newUserCounts.filter((count) => count > 0);
  const averagePerActivePeriod = activePeriods.length
    ? newUserTotal / activePeriods.length
    : 0;
  const peakCount = newUserCounts.length ? Math.max(...newUserCounts) : 0;
  const peakIndex = newUserCounts.findIndex((count) => count === peakCount);
  const periodNoun =
    view === "daily"
      ? "day"
      : view === "weekly"
        ? "week"
        : view === "monthly"
          ? "month"
          : "year";
  const formattedPeakPeriod =
    peakCount > 0 && peakIndex >= 0
      ? (categoryLabelFormatter?.(chart.categories[peakIndex]!) ??
          formatShortDate(chart.categories[peakIndex]!))
      : "—";
  const peakPeriod = Array.isArray(formattedPeakPeriod)
    ? formattedPeakPeriod.join(" · ")
    : formattedPeakPeriod;

  useEffect(() => {
    if (requestKey === lastRequestKey.current) return;
    lastRequestKey.current = requestKey;
    const controller = new AbortController();
    const params = new URLSearchParams({
      report,
      start_date: range.startDate,
      end_date: range.endDate,
    });
    if (report === "revenue" || report === "cost" || report === "new-users") {
      params.set("period", view);
    }

    setLoading(true);
    setError(null);
    void fetch("/api/analytics/session-summary?" + params.toString(), {
      cache: "no-store",
      signal: controller.signal,
    })
      .then(async (response) => {
        const result = (await response.json()) as {
          data: ChartReportData | null;
          error: string | null;
        };
        if (!response.ok || result.error || !result.data) {
          throw new Error(result.error || "Unable to load this chart.");
        }
        setData(result.data);
      })
      .catch((cause: unknown) => {
        if (cause instanceof DOMException && cause.name === "AbortError") return;
        setError(
          cause instanceof Error ? cause.message : "Unable to load this chart.",
        );
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });

    return () => controller.abort();
  }, [report, view, range.startDate, range.endDate, requestKey]);

  const chartPanel = (
    <ChartPanel
      title={title}
      type={
        metric === "returning-users" ||
        metric === "cost" ||
        metric === "revenue-profit" ||
        metric === "energy-bill" ||
        metric === "new-users"
          ? "bar"
          : metric === "mean-charging"
            ? "line"
            : "area"
      }
      stacked={metric === "returning-users"}
      colors={
        metric === "new-users"
          ? ["var(--chart-3)"]
          : metric === "returning-users"
          ? [
              "var(--chart-1)",
              "var(--chart-2)",
              "var(--chart-3)",
              "var(--chart-4)",
              "var(--warning)",
            ]
          : undefined
      }
      categories={chart.categories}
      categoryLabelFormatter={categoryLabelFormatter}
      series={chart.series}
      toolbar={
        <PeriodControls
          view={view}
          onViewChange={setView}
          anchorDate={anchorDate}
          onAnchorDateChange={setAnchorDate}
          range={range}
          dailyRange={dailyRange}
          onDailyRangeChange={setDailyRange}
          today={today}
        />
      }
      paginateDates={false}
      loading={loading}
      error={error}
      bare={metric === "new-users"}
    />
  );

  if (metric !== "new-users") return chartPanel;

  return (
    <Panel
      title={title}
      description={`New registrations · ${formatMainPeriod(view, anchorDate, range)}`}
    >
      <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 px-5 pt-5">
        <span className="size-2.5 rounded-full bg-chart-3" aria-hidden="true" />
        <strong className="text-3xl font-semibold">
          {newUserTotal.toLocaleString()}
        </strong>
        <span className="text-sm text-muted-foreground">
          new registrations in selected period
        </span>
      </div>
      {chartPanel}
      <div className="grid gap-4 border-t px-5 py-4 sm:grid-cols-3">
        <div>
          <p className="text-xs text-muted-foreground">
            Avg. per active {periodNoun}
          </p>
          <p className="mt-1 font-semibold">
            {averagePerActivePeriod.toFixed(1)}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">Peak {periodNoun}</p>
          <p className="mt-1 font-semibold">
            {peakPeriod} {peakCount > 0 ? `· ${peakCount.toLocaleString()}` : ""}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">
            Active {periodNoun}s
          </p>
          <p className="mt-1 font-semibold">{activePeriods.length.toLocaleString()}</p>
        </div>
      </div>
    </Panel>
  );
}
