import { useRef } from "react";
import { useCalendarCell } from "@react-aria/calendar";
import type { CalendarState } from "@react-stately/calendar";
import {
  type CalendarDate,
  isToday,
  getLocalTimeZone,
} from "@internationalized/date";
import { cva } from "class-variance-authority";

export interface CalendarCellProps {
  state: CalendarState;
  date: CalendarDate;
}

export const CalendarCell = ({ state, date }: CalendarCellProps) => {
  const ref = useRef<HTMLDivElement | null>(null);
  const {
    cellProps,
    buttonProps,
    isSelected,
    isOutsideVisibleRange,
    isDisabled,
    formattedDate,
  } = useCalendarCell({ date }, state, ref);

  return (
    <td className="p-0" {...cellProps}>
      <div
        {...buttonProps}
        ref={ref}
        hidden={isOutsideVisibleRange}
        className={cellClasses({
          selected: isSelected,
          disabled: isDisabled,
          today: isToday(date, getLocalTimeZone()),
        })}
      >
        <span className="text-style-M100 inline-flex w-8 items-center justify-center">
          {formattedDate}
        </span>
      </div>
    </td>
  );
};

const cellClasses = cva("rounded-6 px-10 py-4 outline-0", {
  variants: {
    selected: {
      true: "bg-B400 text-N0",
      false: "",
    },
    disabled: {
      true: "text-N60",
      false: "cursor-pointer ring-B400FR focus-visible:ring-3",
    },
    today: {
      true: "",
      false: "",
    },
  },
  compoundVariants: [
    {
      disabled: false,
      today: true,
      class: "text-B400",
    },
    {
      selected: true,
      disabled: false,
      class: "hover:bg-B500",
    },
    {
      selected: false,
      disabled: false,
      class: "hover:bg-N20A",
    },
  ],
});
