"use client";

import { ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useQueryUpdate } from "@/components/shared/query-controls";
import {
  mondayWeekStart,
  shiftCalendarMonths,
  threeMonthPeriodEnd,
} from "./heatmap-period";

const dateFormat = new Intl.DateTimeFormat("en-GB", {
  day: "numeric",
  month: "short",
  timeZone: "UTC",
});

function shiftWeek(value: string, amount: number) {
  const date = new Date(`${value}T00:00:00.000Z`);
  date.setUTCDate(date.getUTCDate() + amount * 7);
  return date.toISOString().slice(0, 10);
}

function formatDateRange(startValue: string, endValue: string) {
  const start = new Date(`${startValue}T00:00:00.000Z`);
  const end = new Date(`${endValue}T00:00:00.000Z`);
  const startLabel = dateFormat.format(start);
  const endLabel = dateFormat.format(end);
  return start.getUTCFullYear() === end.getUTCFullYear()
    ? `${startLabel} – ${endLabel} ${end.getUTCFullYear()}`
    : `${startLabel} ${start.getUTCFullYear()} – ${endLabel} ${end.getUTCFullYear()}`;
}

function formatWeekRange(value: string) {
  const start = new Date(`${value}T00:00:00.000Z`);
  const end = new Date(start);
  end.setUTCDate(end.getUTCDate() + 6);
  return formatDateRange(value, end.toISOString().slice(0, 10));
}

function formatThreeMonthRange(value: string) {
  const end = threeMonthPeriodEnd(value);
  return end ? formatDateRange(value, end) : value;
}

export function SessionStartWeekNavigator({
  value,
  maxDate,
  queryKey,
  chartTitle,
  granularity,
}: {
  value: string;
  maxDate: string;
  queryKey: string;
  chartTitle: string;
  granularity: "week" | "three-month";
}) {
  const updateQuery = useQueryUpdate();
  const latestSelectableStart =
    granularity === "week"
      ? mondayWeekStart(maxDate) ?? value
      : shiftCalendarMonths(maxDate, -3) ?? value;
  const canGoNext = value < latestSelectableStart;
  const periodLabel =
    granularity === "week"
      ? formatWeekRange(value)
      : formatThreeMonthRange(value);
  const shiftPeriod = (amount: number) =>
    granularity === "week"
      ? shiftWeek(value, amount)
      : shiftCalendarMonths(value, amount * 3) ?? value;
  const periodName = granularity === "week" ? "week" : "three-month period";

  return (
    <div
      className="flex items-center justify-center gap-1 sm:gap-3"
      role="group"
      aria-label={`${granularity === "week" ? "Week" : "Three-month period"} for ${chartTitle}`}
    >
      <Button
        type="button"
        variant="ghost"
        size="icon-lg"
        aria-label={`Previous ${periodName}`}
        onClick={() => updateQuery({ [queryKey]: shiftPeriod(-1) })}
      >
        <ChevronLeft className="size-5" aria-hidden="true" />
      </Button>
      <span
        className={`text-center text-sm font-medium tabular-nums ${granularity === "week" ? "min-w-[168px] sm:min-w-[196px]" : "min-w-[208px] sm:min-w-[240px]"}`}
        aria-live="polite"
      >
        {periodLabel}
      </span>
      <Button
        type="button"
        variant="ghost"
        size="icon-lg"
        aria-label={`Next ${periodName}`}
        disabled={!canGoNext}
        onClick={() => updateQuery({ [queryKey]: shiftPeriod(1) })}
      >
        <ChevronRight className="size-5" aria-hidden="true" />
      </Button>
    </div>
  );
}
