import { type RefObject, useRef } from "react";
import {
  useDatePicker,
  type DateValue,
  type DatePickerAria,
} from "@react-aria/datepicker";
import { useDialog, type DialogAria } from "@react-aria/dialog";
import {
  useDatePickerState,
  type DatePickerStateOptions,
  type DatePickerState,
} from "@react-stately/datepicker";

export function useReactAriaDatePicker(
  props: Omit<DatePickerStateOptions<DateValue>, "onChange"> & {
    onChange: ((value: DateValue | null) => void) | undefined;
    autoFocusCalendar?: boolean;
  }
): { ref: RefObject<HTMLElement>; state: DatePickerState } & Omit<
  DatePickerAria,
  "dialogProps"
> & {
    dialogProps: DialogAria["dialogProps"] & {
      ref: RefObject<HTMLDivElement>;
    };
  } {
  const state = useDatePickerState(props);
  const ref = useRef<HTMLElement>(null);
  const dialogRef = useRef<HTMLDivElement>(null);
  const { dialogProps, ...elementProps } = useDatePicker(props, state, ref);
  const dialogBaseProps = useDialog(dialogProps, dialogRef);

  return {
    state,
    ref,
    ...elementProps,
    dialogProps: {
      ...dialogBaseProps.dialogProps,
      ref: dialogRef,
    },
    calendarProps: {
      ...elementProps.calendarProps,
      autoFocus: props.autoFocusCalendar ?? true,
    },
  };
}
