/*!
 * Copyright (c) 2023-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

import styled from "@emotion/styled";
import { DateTimePicker as MuiDateTimePicker } from "@mui/x-date-pickers";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { Button } from "../../Buttons/Button.js";
import { DateFieldActionBar } from "../../DatePickers/DateFieldActionBar.js";
import { DateFieldLocalizationProvider } from "../../DatePickers/DateFieldLocalizationProvider.js";
import { TimeZonePicker } from "../../DatePickers/TimeZonePicker.js";
import { useOdysseyDateFields } from "../../DatePickers/useOdysseyDateFields.js";
import { useTranslation } from "../../i18n.generated/i18n.js";
import { CalendarIcon, ClockIcon } from "../../icons.generated/index.js";
import { useOdysseyDesignTokens } from "../../OdysseyDesignTokensContext.js";
import { OdysseyThemeProvider } from "../../OdysseyThemeProvider.js";
import { pxToRem } from "../../theme/pxToRem.js";
import { useUniqueId } from "../../useUniqueId.js";
import { DateTimeField } from "./DateTimeField.js";
import { dateTimePickerTheme } from "./dateTimePickerTheme.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export const DateTimePickerSize = {
  maxWidth: `${pxToRem(486)}rem`
};
const DatePickerContainer = styled.div({
  ".MuiFormControl-root": {
    marginBlockEnd: 0
  }
});
const DatePickerWidthContainer = styled.div(() => ({
  ".MuiInput-root": {
    width: "100%",
    maxWidth: DateTimePickerSize.maxWidth
  }
}));
const TimeZonePickerContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  marginBlockStart: odysseyDesignTokens.Spacing3
}));
const DateTimePicker = ({
  defaultValue: defaultValueProp,
  errorMessage,
  hint,
  HintLinkComponent,
  id: idOverride,
  isDateEnabled = () => true,
  isDisabled,
  isOptional,
  isReadOnly,
  isMonthEnabled = () => true,
  isYearEnabled = () => true,
  label,
  minDate: minDateProp,
  maxDate: maxDateProp,
  onBlur,
  onCalendarDateChange,
  onInputChange: onInputChangeProp,
  timeZone,
  timeZonePickerLabel,
  timeZoneOptions,
  value: valueProp
}) => {
  const {
    i18n,
    t
  } = useTranslation();
  const inputRef = useRef(null);
  const odysseyDesignTokens = useOdysseyDesignTokens();
  const dateTimePickerId = useUniqueId(idOverride);
  const {
    closeCalendar,
    commonIcons,
    defaultedLanguageCode,
    formatDateTimeToUtcIsoDateString,
    formatDayOfWeek,
    inputValues,
    internalTimeZone,
    isOpen,
    localeText,
    minDate,
    maxDate,
    onInputChange,
    onTimeZoneChange,
    popperElement,
    setPopperElement,
    shouldDisableDate,
    shouldDisableMonth,
    shouldDisableYear,
    toggleCalendarVisibility
  } = useOdysseyDateFields({
    defaultValue: defaultValueProp,
    errorMessage,
    isDateEnabled,
    isMonthEnabled,
    isYearEnabled,
    minDate: minDateProp,
    maxDate: maxDateProp,
    onInputChange: onInputChangeProp,
    timeZone,
    value: valueProp
  });
  const {
    language
  } = i18n;
  const containerRef = useRef(null);
  useEffect(() => {
    setPopperElement(containerRef.current);
  }, [setPopperElement]);
  const formatDateTimeToJsDateStringOnCalendarSelection = useCallback(value => {
    if (value) {
      const dateStringFromDateTime = formatDateTimeToUtcIsoDateString(value);
      if (dateStringFromDateTime) {
        onCalendarDateChange?.({
          value: dateStringFromDateTime,
          timeZone: internalTimeZone
        });
      }
    }
  }, [formatDateTimeToUtcIsoDateString, internalTimeZone, onCalendarDateChange]);
  const renderDateTimeField = useCallback(({
    defaultValue,
    inputRef,
    value
  }) => {
    return _jsx(DateTimeField, {
      defaultValue: defaultValue,
      endAdornment: _jsx(Button, {
        ariaLabel: t("picker.labels.date.choose"),
        label: "",
        onClick: toggleCalendarVisibility,
        size: "small",
        startIcon: _jsx(commonIcons.CalendarIcon, {}),
        variant: "floating"
      }),
      errorMessage: errorMessage,
      hint: hint,
      HintLinkComponent: HintLinkComponent,
      id: dateTimePickerId,
      inputRef: inputRef,
      isDisabled: isDisabled,
      isOptional: isOptional,
      isReadOnly: isReadOnly,
      label: label,
      maxDate: maxDate,
      minDate: minDate,
      onBlur: onBlur,
      onChange: onInputChange,
      timezone: internalTimeZone,
      value: value
    });
  }, [commonIcons, dateTimePickerId, errorMessage, hint, HintLinkComponent, internalTimeZone, isDisabled, isOptional, isReadOnly, label, onBlur, onInputChange, minDate, maxDate, t, toggleCalendarVisibility]);
  const slots = useMemo(() => ({
    actionBar: DateFieldActionBar,
    field: muiProps => renderDateTimeField(muiProps),
    leftArrowIcon: () => _jsx(commonIcons.ArrowLeftIcon, {}),
    rightArrowIcon: () => _jsx(commonIcons.ArrowRightIcon, {}),
    switchViewIcon: () => _jsx(commonIcons.ChevronDownIcon, {})
  }), [commonIcons, renderDateTimeField]);
  const slotProps = useMemo(() => ({
    actionBar: ({
      wrapperVariant,
      onAccept,
      onCancel
    }) => ({
      actions: wrapperVariant === "desktop" ? [] : ["accept", "cancel"],
      onAccept,
      onCancel
    }),
    popper: {
      anchorEl: popperElement
    },
    tabs: {
      dateIcon: _jsx(CalendarIcon, {}),
      timeIcon: _jsx(ClockIcon, {})
    },
    toolbar: {
      toolbarPlaceholder: ""
    }
  }), [popperElement]);
  return _jsx(OdysseyThemeProvider, {
    themeOverride: dateTimePickerTheme,
    children: _jsxs(DateFieldLocalizationProvider, {
      defaultedLanguageCode: defaultedLanguageCode,
      localeText: localeText,
      children: [_jsx(DatePickerContainer, {
        children: _jsx(DatePickerWidthContainer, {
          odysseyDesignTokens: odysseyDesignTokens,
          ref: containerRef,
          children: _jsx(MuiDateTimePicker, {
            dayOfWeekFormatter: formatDayOfWeek,
            defaultValue: inputValues?.defaultValue,
            disabled: isDisabled,
            fixedWeekNumber: 6,
            inputRef: inputRef,
            label: label,
            maxDate: maxDate,
            minDate: minDate,
            onChange: formatDateTimeToJsDateStringOnCalendarSelection,
            onClose: closeCalendar,
            open: isOpen,
            readOnly: isReadOnly,
            shouldDisableDate: shouldDisableDate,
            shouldDisableMonth: shouldDisableMonth,
            shouldDisableYear: shouldDisableYear,
            slotProps: slotProps,
            slots: slots,
            timezone: internalTimeZone,
            value: inputValues?.value
          }, language)
        })
      }), timeZoneOptions && timeZonePickerLabel && _jsx(TimeZonePickerContainer, {
        odysseyDesignTokens: odysseyDesignTokens,
        children: _jsx(TimeZonePicker, {
          isReadOnly: isReadOnly,
          label: timeZonePickerLabel,
          onTimeZoneChange: onTimeZoneChange,
          timeZoneOptions: timeZoneOptions,
          value: internalTimeZone
        })
      })]
    })
  });
};
const MemoizedDateTimePicker = memo(DateTimePicker);
MemoizedDateTimePicker.displayName = "DateTimePicker";
export { MemoizedDateTimePicker as DateTimePicker };
//# sourceMappingURL=DateTimePicker.js.map