/*!
 * 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 { DatePicker as MuiDatePicker } from "@mui/x-date-pickers";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { Button } from "../Buttons/Button.js";
import { useTranslation } from "../i18n.generated/i18n.js";
import { useOdysseyDesignTokens } from "../OdysseyDesignTokensContext.js";
import { OdysseyThemeProvider } from "../OdysseyThemeProvider.js";
import { useUniqueId } from "../useUniqueId.js";
import { DateField } from "./DateField.js";
import { DateFieldActionBar } from "./DateFieldActionBar.js";
import { DateFieldLocalizationProvider } from "./DateFieldLocalizationProvider.js";
import { datePickerTheme } from "./datePickerTheme.js";
import { TimeZonePicker } from "./TimeZonePicker.js";
import { useOdysseyDateFields } from "./useOdysseyDateFields.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const DatePickerContainer = styled.div({
  ".MuiFormControl-root": {
    marginBlockEnd: 0
  }
});
const DatePickerWidthContainer = styled.div(({
  odysseyDesignTokens
}) => ({
  ".MuiInput-root": {
    width: "100%",
    maxWidth: odysseyDesignTokens.TypographyLineLengthMax
  }
}));
const TimeZonePickerContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  marginBlockStart: odysseyDesignTokens.Spacing3
}));
const DatePicker = ({
  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 datePickerId = 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 renderDateField = useCallback(({
    defaultValue,
    inputRef,
    value
  }) => {
    return _jsx(DateField, {
      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: datePickerId,
      inputRef: inputRef,
      isDisabled: isDisabled,
      isOptional: isOptional,
      isReadOnly: isReadOnly,
      label: label,
      maxDate: maxDate,
      minDate: minDate,
      onBlur: onBlur,
      onChange: onInputChange,
      timezone: internalTimeZone,
      value: value
    });
  }, [commonIcons, datePickerId, errorMessage, hint, HintLinkComponent, internalTimeZone, isDisabled, isOptional, isReadOnly, label, onBlur, onInputChange, minDate, maxDate, t, toggleCalendarVisibility]);
  const slots = useMemo(() => ({
    actionBar: DateFieldActionBar,
    field: muiProps => renderDateField(muiProps),
    leftArrowIcon: () => _jsx(commonIcons.ArrowLeftIcon, {}),
    rightArrowIcon: () => _jsx(commonIcons.ArrowRightIcon, {}),
    switchViewIcon: () => _jsx(commonIcons.ChevronDownIcon, {})
  }), [commonIcons, renderDateField]);
  const slotProps = useMemo(() => ({
    actionBar: ({
      wrapperVariant,
      onAccept,
      onCancel
    }) => ({
      actions: wrapperVariant === "desktop" ? [] : ["accept", "cancel"],
      onAccept,
      onCancel
    }),
    popper: {
      anchorEl: popperElement
    },
    toolbar: {
      toolbarPlaceholder: ""
    }
  }), [popperElement]);
  return _jsx(OdysseyThemeProvider, {
    themeOverride: datePickerTheme,
    children: _jsxs(DateFieldLocalizationProvider, {
      defaultedLanguageCode: defaultedLanguageCode,
      localeText: localeText,
      children: [_jsx(DatePickerContainer, {
        children: _jsx(DatePickerWidthContainer, {
          odysseyDesignTokens: odysseyDesignTokens,
          ref: containerRef,
          children: _jsx(MuiDatePicker, {
            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 MemoizedDatePicker = memo(DatePicker);
MemoizedDatePicker.displayName = "DatePicker";
export { MemoizedDatePicker as DatePicker };
//# sourceMappingURL=DatePicker.js.map