"use client";

import type { ReactNode } from "react";
import type { Locale } from "date-fns";

import { cn } from "@/lib/utils";
import { useTranslation } from "@/hooks/useTranslation";
import { Typography } from "@/components/ui/typography";

import { DEFAULT_EVENT_COLOR, EVENT_COLOR_CLASSES } from "./constants";
import { formatTime } from "./lib/date-utils";
import type { CalendarEvent } from "./types";

interface DayEventsListProps<TMeta> {
  events: CalendarEvent<TMeta>[];
  locale: Locale;
  onSelect: (event: CalendarEvent<TMeta>) => void;
  renderEvent?: (event: CalendarEvent<TMeta>) => ReactNode;
}

/** Scrollable list of one day's bookings — a row drills into the event. */
export function DayEventsList<TMeta>({
  events,
  locale,
  onSelect,
  renderEvent,
}: DayEventsListProps<TMeta>) {
  const { t } = useTranslation();

  // No local max-h/overflow: the dialog's own body is the scroll region, and a
  // second scroller nested inside it gives two scrollbars and a list that stops
  // at 320px while the sheet still has room.
  return (
    <ul className="flex flex-col gap-1">
      {events.map((event) => {
        const color = EVENT_COLOR_CLASSES[event.color ?? DEFAULT_EVENT_COLOR];
        return (
          <li key={event.id}>
            <button
              type="button"
              onClick={() => onSelect(event)}
              className="flex w-full items-center gap-3 rounded-[10px] p-2 text-start hover:bg-muted"
            >
              {renderEvent ? (
                renderEvent(event)
              ) : (
                <>
                  <span
                    className={cn("size-2.5 shrink-0 rounded-full", color.dot)}
                    aria-hidden
                  />
                  <Typography
                    as="span"
                    variant="caption"
                    color="secondary"
                    className="w-16 shrink-0"
                  >
                    {event.allDay
                      ? t("calendar.allDay")
                      : formatTime(event.start, locale)}
                  </Typography>
                  <Typography as="span" variant="body" className="truncate">
                    {event.title}
                  </Typography>
                </>
              )}
            </button>
          </li>
        );
      })}
    </ul>
  );
}
