import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useCalendarContext } from "./calendar-context";
import type { CalendarCellProps } from "./calendar.props";

/** A single day cell in the calendar grid. Handles selection, disabled, today, and outside-month states. */
export function CalendarCell(props: CalendarCellProps): JSX.Element {
  const [local, rest] = splitProps(props, ["date", "children"]);
  const ctx = useCalendarContext();

  const isOutsideMonth = () => {
    const d = new Date(local.date + "T00:00:00");
    return d.getMonth() !== ctx.displayMonth();
  };

  const handleClick = () => {
    if (!ctx.isDateDisabled(local.date)) {
      ctx.selectDate(local.date);
    }
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      handleClick();
    }
  };

  return (
    <td
      data-scope="calendar"
      data-part="cell"
      data-selected={ctx.isDateSelected(local.date) ? "" : undefined}
      data-today={ctx.isDateToday(local.date) ? "" : undefined}
      data-disabled={ctx.isDateDisabled(local.date) ? "" : undefined}
      data-outside-month={isOutsideMonth() ? "" : undefined}
      aria-selected={ctx.isDateSelected(local.date)}
      aria-disabled={ctx.isDateDisabled(local.date)}
      tabindex={ctx.isDateDisabled(local.date) ? -1 : 0}
      role="gridcell"
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      {...rest}
    >
      {local.children}
    </td>
  );
}
