import {useMemo, useState} from 'react';
import {
  DateValue,
  getLocalTimeZone,
  toZoned,
  ZonedDateTime,
} from '@internationalized/date';
import {useDateFormatter} from '../../../../i18n/use-date-formatter';
import {getDefaultGranularity} from './utils';
import type {DatePickerValueProps} from './date-picker/use-date-picker-state';
import {DateRangeValue} from './date-range-picker/date-range-value';

export function useBaseDatePickerState(
  selectedDate: DateValue,
  props:
    | DatePickerValueProps<ZonedDateTime>
    | DatePickerValueProps<Partial<DateRangeValue>>
) {
  const [calendarIsOpen, setCalendarIsOpen] = useState(false);
  const closeDialogOnSelection = props.closeDialogOnSelection ?? true;

  const defaultFormatter = useDateFormatter();
  const resolvedOptions = useMemo(
    () => defaultFormatter.resolvedOptions(),
    [defaultFormatter]
  );
  const timeZone = useMemo(
    () =>
      selectedDate && 'timeZone' in selectedDate
        ? selectedDate.timeZone
        : resolvedOptions.timeZone,
    [selectedDate, resolvedOptions.timeZone]
  );

  const granularity = props.granularity || getDefaultGranularity(selectedDate);
  const min = props.min ? toZoned(props.min, getLocalTimeZone()) : undefined;
  const max = props.max ? toZoned(props.max, getLocalTimeZone()) : undefined;

  return {
    timeZone,
    granularity,
    min,
    max,
    calendarIsOpen,
    setCalendarIsOpen,
    closeDialogOnSelection,
  };
}
