'use client';

import type { ReactNode } from 'react';
import { cn } from '@/lib/utils/cn';

/**
 * MT-13 (M-06): the booking page's month calendar, shared by the scheduling page editor's live
 * preview and the public booking page (/book/:slug), so the preview is what visitors get:
 * ‹ month ›, the weekdays, and the month's dates, those with free times enabled.
 * Each page passes its own class names (the editor's `gm-*`, the public page's).
 */

const MONTH_FMT = new Intl.DateTimeFormat('en-US', { month: 'long', year: 'numeric' });
const FULL_FMT = new Intl.DateTimeFormat('en-US', {
  weekday: 'long',
  month: 'long',
  day: 'numeric',
  year: 'numeric',
});
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export type MonthCalendarClasses = {
  row: string;
  nav: string;
  weekdays: string;
  dates: string;
  empty: string;
};

/** The dates of `month` (its first day, local midnight), as local days. */
export function monthDays(month: Date): Date[] {
  const n = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
  return Array.from(
    { length: n },
    (_, i) => new Date(month.getFullYear(), month.getMonth(), i + 1),
  );
}

export function MonthCalendar({
  month,
  onMonth,
  canPrev,
  canNext,
  selected,
  today,
  isOpen,
  onPick,
  classes,
  prevIcon,
  nextIcon,
}: {
  /** The first day of the month shown (local midnight). */
  month: Date;
  onMonth: (month: Date) => void;
  canPrev: boolean;
  canNext: boolean;
  selected: Date | null;
  today: Date;
  /** Whether a date can be picked (it has free times). */
  isOpen: (date: Date) => boolean;
  onPick: (date: Date) => void;
  classes: MonthCalendarClasses;
  prevIcon: ReactNode;
  nextIcon: ReactNode;
}) {
  const step = (n: number) => onMonth(new Date(month.getFullYear(), month.getMonth() + n, 1));
  return (
    <>
      <div className={classes.row}>
        <button
          type="button"
          className={classes.nav}
          aria-label="Previous month"
          disabled={!canPrev}
          onClick={() => step(-1)}
        >
          {prevIcon}
        </button>
        <p>{MONTH_FMT.format(month)}</p>
        <button
          type="button"
          className={classes.nav}
          aria-label="Next month"
          disabled={!canNext}
          onClick={() => step(1)}
        >
          {nextIcon}
        </button>
      </div>
      <div className={classes.weekdays}>
        {WEEKDAYS.map((d) => (
          <span key={d}>{d}</span>
        ))}
      </div>
      <div className={classes.dates} aria-label="Choose a date">
        {Array.from({ length: month.getDay() }, (_, i) => (
          <span className={classes.empty} aria-hidden="true" key={`e${i}`} />
        ))}
        {monthDays(month).map((date) => {
          const isSel = selected !== null && date.getTime() === selected.getTime();
          return (
            <button
              type="button"
              key={date.getDate()}
              aria-label={FULL_FMT.format(date)}
              aria-pressed={isSel || undefined}
              className={cn(
                isSel && 'is-selected',
                date.getTime() === today.getTime() && 'is-today',
              )}
              disabled={!isOpen(date)}
              onClick={() => onPick(date)}
            >
              {date.getDate()}
            </button>
          );
        })}
      </div>
    </>
  );
}
