import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _typeof from '@babel/runtime/helpers/typeof';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.from.js';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.slice.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.regexp.constructor.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.regexp.to-string.js';
import 'core-js/modules/es.string.includes.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import React__default, { useRef, useState, useEffect, useMemo, useCallback } from 'react';
import ReactDOM__default from 'react-dom';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import { TextInput } from '@carbon/react';
import classnames from 'classnames';
import { settings } from '../../constants/Settings.js';
import { keyboardKeys } from '../../constants/KeyCodeConstants.js';
import useMerged from '../../hooks/useMerged.js';
import ListSpinner from './ListSpinner.js';
import { WarningFilled, WarningAltFilled, EditOff, Time } from '@carbon/icons-react';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = settings.iotPrefix,
  prefix = settings.prefix;
var TIME_FORMAT = {
  12: 'hh:mm A',
  24: 'HH:mm'
};
var AVAILABLE_FORMATS = 'hhHHmmA';
var timeUtils = {
  get12Hours: function get12Hours(selectedTime, currentTime) {
    return /(0[1-9])|(1[0-2])/.test(selectedTime.substring(0, 2)) ? selectedTime.substring(0, 2) : currentTime.substring(0, 2);
  },
  get24Hours: function get24Hours(selectedTime, currentTime) {
    return /^(2[0-3]|[01]?[0-9])$/.test(selectedTime.substring(0, 2)) ? selectedTime.substring(0, 2) : currentTime.substring(2, 4);
  },
  getMinutes: function getMinutes(selectedTime, currentTime) {
    return /[0-5][0-9]/.test(selectedTime.substring(3, 5)) ? selectedTime.substring(3, 5) : currentTime.substring(4, 6);
  },
  getMeridiem: function getMeridiem(selectedTime, currentTime, amString, pmString) {
    return new RegExp("[".concat(amString, "|").concat(pmString, "]")).test(selectedTime.substring(selectedTime.length - 2)) ? selectedTime.substring(selectedTime.length - 2) : currentTime.substring(6);
  }
};
var propTypes = {
  className: PropTypes.string,
  id: PropTypes.string.isRequired,
  /** Specify the value for input */
  value: PropTypes.string,
  /** Specify the value for secondary input (range) */
  secondaryValue: PropTypes.string,
  /** Specify whether the input labels to be visually hidden */
  hideLabel: PropTypes.bool,
  /** Specify whether the secondary label to be visually hidden */
  hideSecondaryLabel: PropTypes.bool,
  /** Input can be for a single time or a range - defaults to single */
  type: PropTypes.oneOf(['single', 'range']),
  i18n: PropTypes.shape({
    /** Label for input (will be first, if range type) */
    labelText: PropTypes.string.isRequired,
    helperText: PropTypes.string,
    /** Label for second input in range */
    secondaryLabelText: PropTypes.string,
    secondaryHelperText: PropTypes.string,
    invalidText: PropTypes.string,
    warnText: PropTypes.string,
    timeIconText: PropTypes.string,
    placeholderText: PropTypes.string,
    placeholderText24h: PropTypes.string,
    amString: PropTypes.string,
    pmString: PropTypes.string
  }),
  /** Size of input */
  size: PropTypes.oneOf(['sm', 'md', 'lg']),
  /** Specify whether the control is currently disabled */
  disabled: PropTypes.bool,
  /** Specify whether the control is currently read only */
  readOnly: PropTypes.bool,
  /** Specify whether the control is currently in warning state */
  warn: PropTypes.arrayOf(PropTypes.bool),
  /** Specify whether the control is currently in invalid state */
  invalid: PropTypes.arrayOf(PropTypes.bool),
  /** Boolean to swap for light theme */
  light: PropTypes.bool,
  /** Optional handler that is called whenever <input> is updated - will be called with new value as an argument */
  onChange: PropTypes.func,
  testId: PropTypes.string,
  style: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
  is24hours: PropTypes.bool
};

/* istanbul ignore next */
var defaultProps = {
  className: undefined,
  hideLabel: false,
  value: undefined,
  secondaryValue: undefined,
  hideSecondaryLabel: false,
  type: 'single',
  i18n: {
    invalidText: 'The time entered is invalid',
    warnText: undefined,
    timeIconText: 'Open time picker',
    placeholderText: 'hh:mm XM',
    placeholderText24h: 'HH:mm',
    readOnlyBtnText: 'Read only',
    amString: 'AM',
    pmString: 'PM'
  },
  size: 'md',
  disabled: false,
  readOnly: false,
  warn: [false, false],
  invalid: [false, false],
  light: false,
  onChange: function onChange() {},
  testId: 'time-picker',
  style: {},
  is24hours: false
};
var validate = function validate(newValue, is24hours, amString, pmString) {
  if (is24hours) {
    return /^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$/.test(newValue) || newValue === '';
  }
  var timeRegEx = /^((0[1-9])?|(1[0-2])?)*:[0-5][0-9]/;
  var meridianRegEx = new RegExp("".concat(amString, "|").concat(pmString));
  return timeRegEx.test(newValue.split(' ')[0]) && meridianRegEx.test(newValue.split(' ')[1]) || newValue === '';
};
var TimePickerDropdown = function TimePickerDropdown(_ref) {
  var id = _ref.id,
    className = _ref.className,
    type = _ref.type,
    i18n = _ref.i18n,
    size = _ref.size,
    disabled = _ref.disabled,
    testId = _ref.testId,
    warn = _ref.warn,
    invalid = _ref.invalid,
    light = _ref.light,
    readOnly = _ref.readOnly,
    hideLabel = _ref.hideLabel,
    hideSecondaryLabel = _ref.hideSecondaryLabel,
    value = _ref.value,
    secondaryValue = _ref.secondaryValue,
    onChange = _ref.onChange,
    style = _ref.style,
    is24hours = _ref.is24hours;
  var init = useRef(false);
  var inputRef = useRef();
  var secondaryInputRef = useRef();
  var dropDownRef = useRef();
  var container = inputRef.current;
  var invalidProp = invalid[0];
  var secondaryInvalidProp = invalid[1];
  var warnProp = warn[0];
  var secondaryWarnProp = warn[1];
  // Component state
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    openState = _useState2[0],
    setOpenState = _useState2[1];
  var _useState3 = useState([0, 0]),
    _useState4 = _slicedToArray(_useState3, 2),
    position = _useState4[0],
    setPosition = _useState4[1];
  var _useState5 = useState(0),
    _useState6 = _slicedToArray(_useState5, 2),
    focusedInput = _useState6[0],
    setFocusedInput = _useState6[1];
  var _useState7 = useState(value || ''),
    _useState8 = _slicedToArray(_useState7, 2),
    valueState = _useState8[0],
    setValueState = _useState8[1];
  var _useState9 = useState(secondaryValue || ''),
    _useState10 = _slicedToArray(_useState9, 2),
    secondaryValueState = _useState10[0],
    setSecondaryValueState = _useState10[1];
  var _useState11 = useState(invalidProp),
    _useState12 = _slicedToArray(_useState11, 2),
    invalidState = _useState12[0],
    setInvalidState = _useState12[1];
  var _useState13 = useState(secondaryInvalidProp),
    _useState14 = _slicedToArray(_useState13, 2),
    secondaryInvalidState = _useState14[0],
    setSecondaryInvalidState = _useState14[1];
  useEffect(function () {
    if (init.current) {
      onChange(valueState, secondaryValueState);
    } else {
      init.current = true;
    }
  }, [onChange, secondaryValueState, valueState, init]);
  useEffect(function () {
    setInvalidState(invalidProp);
    setSecondaryInvalidState(secondaryInvalidProp);
  }, [invalidProp, secondaryInvalidProp]);
  useEffect(function () {
    if (container) {
      var _container$getBoundin = container.getBoundingClientRect(),
        left = _container$getBoundin.left,
        bottom = _container$getBoundin.bottom;
      setPosition([left, bottom]);
    }
  }, [container, hideLabel]);
  var _useMerged = useMerged(defaultProps.i18n, i18n),
    labelText = _useMerged.labelText,
    secondaryLabelText = _useMerged.secondaryLabelText,
    helperText = _useMerged.helperText,
    invalidText = _useMerged.invalidText,
    warnText = _useMerged.warnText,
    timeIconText = _useMerged.timeIconText,
    placeholderText = _useMerged.placeholderText,
    placeholderText24h = _useMerged.placeholderText24h,
    readOnlyBtnText = _useMerged.readOnlyBtnText,
    amString = _useMerged.amString,
    pmString = _useMerged.pmString;
  useEffect(function () {
    if (openState) {
      var _container$getBoundin2 = container.getBoundingClientRect(),
        left = _container$getBoundin2.left,
        bottom = _container$getBoundin2.bottom,
        top = _container$getBoundin2.top;
      var dropdownHeight = 280;
      var scrollOffset = window.pageYOffset;
      var dropdownBottom = bottom + dropdownHeight;
      var dropdownPos = top - dropdownHeight + scrollOffset;
      if (dropdownBottom > window.innerHeight && dropdownPos > 0) {
        setPosition([left, dropdownPos]);
      } else {
        setPosition([left, bottom + scrollOffset]);
      }
    }
  }, [container, openState, focusedInput, is24hours, value, secondaryValue]);
  var handleOpenDropdown = function handleOpenDropdown(index) {
    if (focusedInput === index && openState === true) {
      setOpenState(false);
    } else {
      setOpenState(true);
    }
    setFocusedInput(index);
  };
  var handleOnFocus = function handleOnFocus(index) {
    setFocusedInput(index);
    if (!readOnly) {
      handleOpenDropdown(index);
      var current12HourTime = dayjs().format(TIME_FORMAT[12]).split(' ')[0];
      var current12HourMeridian = dayjs().format(TIME_FORMAT[12]).split(' ')[1] === 'AM' ? amString : pmString;
      var currentTime = is24hours ? dayjs().format(TIME_FORMAT[24]) : "".concat(current12HourTime, " ").concat(current12HourMeridian);
      if (index === 0 && !value) {
        setValueState(function (prevValue) {
          return prevValue || currentTime;
        });
      }
      if (index === 1 && !secondaryValue) {
        setSecondaryValueState(function (prevValue) {
          return prevValue || currentTime;
        });
      }
    }
  };
  var handleOnKeyDown = function handleOnKeyDown(e) {
    if (e.key === keyboardKeys.ESCAPE) {
      setOpenState(false);
    }
    if (e.key === keyboardKeys.DOWN && dropDownRef.current) {
      dropDownRef.current.focus();
    }
  };
  var handleOnKeyUp = function handleOnKeyUp(e) {
    if (e.key === keyboardKeys.ENTER && inputRef.current) {
      setOpenState(false);
      inputRef.current.focus();
    }
  };
  var handleOnChange = function handleOnChange(e) {
    var val = e;
    if (_typeof(e) === 'object') {
      val = e.target.value;
    }

    // match all the words combined provided by amString and pmString
    var isValidMeridian = new RegExp("[".concat(amString).concat(pmString, "]")).test(val.substring(val.length - 1));
    var isValidTime = /[0-9: ]/.test(val.substring(val.length - 1));
    // @TODO: detect the length and run validation for as many as we can
    // This value is pasted in or autocompleted
    // istanbul ignore else

    // match any of the full string of tranlated AM or PM
    var meridianRegEx = new RegExp("".concat(amString, "|").concat(pmString, "|").concat(defaultProps.i18n.amString, "|").concat(defaultProps.i18n.pmString), 'g');
    var newVal = val && meridianRegEx.test(val) && !is24hours ? val.split(' ')[1] === 'AM' || val.split(' ')[1] === amString ? "".concat(val.split(' ')[0], " ").concat(amString) : "".concat(val.split(' ')[0], " ").concat(pmString) : val;
    if (val.length > 1) {
      if (focusedInput === 0) {
        setValueState(newVal);
      } else {
        setSecondaryValueState(newVal);
      }
    } else if (isValidMeridian || isValidTime || val === '') {
      if (focusedInput === 0) {
        setValueState(newVal);
      } else {
        setSecondaryValueState(newVal);
      }
    }
  };
  var handleOnBlur = function handleOnBlur(e) {
    var _dropDownRef$current, _e$relatedTarget, _e$relatedTarget2;
    var contained = ((_dropDownRef$current = dropDownRef.current) === null || _dropDownRef$current === void 0 ? void 0 : _dropDownRef$current.contains(e.relatedTarget)) || e.currentTarget.contains(e.relatedTarget) || ((_e$relatedTarget = e.relatedTarget) === null || _e$relatedTarget === void 0 || (_e$relatedTarget = _e$relatedTarget.parentNode) === null || _e$relatedTarget === void 0 ? void 0 : _e$relatedTarget.classList[0].includes('iot--list-spinner')) || ((_e$relatedTarget2 = e.relatedTarget) === null || _e$relatedTarget2 === void 0 || (_e$relatedTarget2 = _e$relatedTarget2.parentNode) === null || _e$relatedTarget2 === void 0 ? void 0 : _e$relatedTarget2.classList[0].includes('iot--list-spinner'));
    if (!contained) {
      // close dropdown and validate
      setOpenState(false);
      setInvalidState(!validate(inputRef.current.value, is24hours, amString, pmString));
      /* istanbul ignore else */
      if (secondaryInputRef.current) {
        setSecondaryInvalidState(!validate(secondaryInputRef.current.value, is24hours, amString, pmString));
      }
    }
  };
  var inputState = useMemo(function () {
    return {
      state: invalidState && !readOnly ? 'invalid' : warnProp && !readOnly ? 'warn' : readOnly ? 'readOnly' : 'default',
      secondaryState: secondaryInvalidState && !readOnly ? 'invalid' : secondaryWarnProp && !readOnly ? 'warn' : readOnly ? 'readOnly' : 'default',
      firstIcon: invalidState && !readOnly ? WarningFilled : warnProp && !readOnly ? WarningAltFilled : readOnly ? EditOff : Time,
      secondIcon: secondaryInvalidState && !readOnly ? WarningFilled : secondaryWarnProp && !readOnly ? WarningAltFilled : readOnly ? EditOff : Time,
      text: !readOnly && invalidState ? invalidText : !readOnly && warnProp ? warnText : helperText,
      secondaryText: !readOnly && secondaryInvalidState ? invalidText : !readOnly && secondaryWarnProp ? warnText : helperText
    };
  }, [invalidState, secondaryInvalidState, warnProp, secondaryWarnProp, readOnly, invalidText, warnText, helperText]);
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/no-static-element-interactions
    React__default.createElement("div", {
      onBlur: handleOnBlur,
      onKeyDown: handleOnKeyDown,
      onKeyUp: handleOnKeyUp,
      "data-testid": testId,
      className: classnames("".concat(iotPrefix, "--time-picker"), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, className, className), "".concat(iotPrefix, "--time-picker--24h"), is24hours), "".concat(iotPrefix, "--time-picker--light"), light), "".concat(iotPrefix, "--time-picker--disabled"), disabled), "".concat(iotPrefix, "--time-picker-range"), type === 'range'), "".concat(iotPrefix, "--time-picker--warn"), inputState.state === 'warn' || inputState.secondaryState === 'warn' || warn[0] || warn[1]))
    }, type === 'single' ? /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("div", {
      className: classnames("".concat(iotPrefix, "--time-picker__wrapper ").concat(iotPrefix, "--time-picker__wrapper-").concat(size), _defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__wrapper--selected"), focusedInput === 0 && openState), "".concat(iotPrefix, "--time-picker--invalid"), inputState.state === 'invalid'))
    }, /*#__PURE__*/React__default.createElement(TextInput, {
      onChange: handleOnChange,
      "data-testid": "".concat(testId, "-input"),
      id: id,
      value: valueState,
      onFocus: function onFocus() {
        return handleOnFocus(0);
      },
      readOnly: readOnly,
      hideLabel: hideLabel,
      labelText: labelText,
      placeholder: is24hours ? placeholderText24h : placeholderText,
      size: size,
      warn: warnProp,
      invalid: invalidState,
      light: light,
      disabled: disabled,
      ref: inputRef
    }), /*#__PURE__*/React__default.createElement("div", {
      "data-testid": "".concat(testId, "-time-btn"),
      title: readOnly ? readOnlyBtnText : timeIconText,
      className: classnames("".concat(iotPrefix, "--time-picker__icon"), _defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__icon--invalid"), invalidState), "".concat(iotPrefix, "--time-picker__icon--warn"), warnProp), "".concat(iotPrefix, "--time-picker__icon--readonl"), readOnly))
    }, /*#__PURE__*/React__default.createElement(inputState.firstIcon, {
      "aria-hidden": "true",
      focusable: false
    }))), /*#__PURE__*/React__default.createElement("p", {
      "data-testid": "".concat(testId, "-helpertext"),
      className: classnames("".concat(prefix, "--form__helper-text"), _defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__helper-text"), invalidState), "".concat(prefix, "--form__helper-text--disabled"), disabled), "".concat(iotPrefix, "--time-picker--invalid"), inputState.state === 'invalid'))
    }, !readOnly && invalidState ? invalidText : !readOnly && warnProp ? warnText : helperText)) : /*#__PURE__*/React__default.createElement("fieldset", null, hideSecondaryLabel && !hideLabel ? /*#__PURE__*/React__default.createElement("legend", {
      id: "".concat(id, "-label"),
      className: classnames("".concat(prefix, "--label"), _defineProperty({}, "".concat(prefix, "--label--disabled"), disabled))
    }, labelText) : null, /*#__PURE__*/React__default.createElement("div", {
      className: classnames("".concat(iotPrefix, "--time-picker__wrapper ").concat(iotPrefix, "--time-picker__wrapper-").concat(size), _defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__wrapper--selected"), focusedInput === 0 && openState), "".concat(iotPrefix, "--time-picker--invalid"), inputState.state === 'invalid'))
    }, /*#__PURE__*/React__default.createElement(TextInput, {
      onChange: handleOnChange,
      "data-testid": "".concat(testId, "-input-1"),
      onFocus: function onFocus() {
        return handleOnFocus(0);
      },
      id: "".concat(id, "-1"),
      readOnly: readOnly,
      value: valueState,
      hideLabel: hideSecondaryLabel || hideLabel,
      "aria-labelledby": hideSecondaryLabel ? "".concat(id, "-label") : undefined,
      className: "".concat(iotPrefix, "--time-picker-range__text-input-wrapper"),
      labelText: !hideSecondaryLabel ? labelText : '',
      placeholder: is24hours ? placeholderText24h : placeholderText,
      size: size,
      warn: warnProp,
      invalid: invalidState,
      light: light,
      disabled: disabled,
      ref: inputRef
    }), /*#__PURE__*/React__default.createElement("div", {
      "data-testid": "".concat(testId, "-time-btn-1"),
      title: readOnly ? readOnlyBtnText : timeIconText,
      className: classnames("".concat(iotPrefix, "--time-picker__icon"), _defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__icon--invalid"), invalidState), "".concat(iotPrefix, "--time-picker__icon--warn"), warnProp), "".concat(iotPrefix, "--time-picker__icon--readonl"), readOnly))
    }, /*#__PURE__*/React__default.createElement(inputState.firstIcon, {
      "aria-hidden": "true",
      focusable: false
    }))), /*#__PURE__*/React__default.createElement("div", {
      className: classnames("".concat(iotPrefix, "--time-picker__wrapper ").concat(iotPrefix, "--time-picker__wrapper-").concat(size), _defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__wrapper--selected"), focusedInput === 1 && openState), "".concat(iotPrefix, "--time-picker--invalid"), inputState.secondaryState === 'invalid'))
    }, /*#__PURE__*/React__default.createElement(TextInput, {
      "data-testid": "".concat(testId, "-input-2"),
      id: "".concat(id, "-2"),
      onChange: handleOnChange,
      onFocus: function onFocus() {
        return handleOnFocus(1);
      },
      readOnly: readOnly,
      value: secondaryValueState,
      hideLabel: hideSecondaryLabel || hideLabel,
      "aria-labelledby": hideSecondaryLabel ? "".concat(id, "-label") : undefined,
      className: "".concat(iotPrefix, "--time-picker-range__text-input-wrapper"),
      labelText: !hideSecondaryLabel ? secondaryLabelText : '',
      placeholder: is24hours ? placeholderText24h : placeholderText,
      size: size,
      warn: secondaryWarnProp,
      invalid: secondaryInvalidState,
      light: light,
      disabled: disabled,
      ref: secondaryInputRef
    }), /*#__PURE__*/React__default.createElement("div", {
      "data-testid": "".concat(testId, "-time-btn-2"),
      title: readOnly ? readOnlyBtnText : timeIconText,
      className: classnames("".concat(iotPrefix, "--time-picker__icon"), _defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--time-picker__icon--invalid"), secondaryInvalidState), "".concat(iotPrefix, "--time-picker__icon--warn"), secondaryWarnProp), "".concat(iotPrefix, "--time-picker__icon--readonly"), readOnly))
    }, /*#__PURE__*/React__default.createElement(inputState.secondIcon, {
      "aria-hidden": "true",
      focusable: false
    }))), /*#__PURE__*/React__default.createElement("p", {
      "data-testid": "".concat(testId, "-range__helper-text"),
      className: classnames("".concat(prefix, "--form__helper-text"), "".concat(iotPrefix, "--time-picker-range__helper-text"), _defineProperty(_defineProperty({}, "".concat(prefix, "--form__helper-text--disabled"), disabled), "".concat(iotPrefix, "--time-picker--invalid"), inputState.state === 'invalid'))
    }, inputState.text), /*#__PURE__*/React__default.createElement("p", {
      "data-testid": "".concat(testId, "-range__helper-text--secondary"),
      className: classnames("".concat(prefix, "--form__helper-text"), "".concat(iotPrefix, "--time-picker-range__helper-text--secondary"), _defineProperty(_defineProperty({}, "".concat(prefix, "--form__helper-text--disabled"), disabled), "".concat(iotPrefix, "--time-picker--invalid"), inputState.secondaryState === 'invalid'))
    }, inputState.secondaryText)), openState ? /*#__PURE__*/React__default.createElement(TimePickerSpinner, {
      onChange: handleOnChange,
      focusedInput: focusedInput,
      value: focusedInput === 0 ? valueState : secondaryValueState,
      testId: "".concat(testId, "-spinner"),
      position: position,
      ref: dropDownRef,
      style: style,
      is24hours: is24hours,
      amString: amString,
      pmString: pmString
    }) : null)
  );
};
var listItemsForVertical24Hours = Array.from(Array(24)).map(function (el, i) {
  var index = i < 10 ? "0".concat(i) : "".concat(i);
  return {
    id: index,
    value: index
  };
});
var listItemsForVertical12Hours = listItemsForVertical24Hours.slice(1, 13);
var listItemsForVerticalMinutes = Array.from(Array(60)).map(function (el, i) {
  var index = i < 10 ? "0".concat(i) : "".concat(i);
  return {
    id: index,
    value: index
  };
});
var listItemsForVerticalMeridiem = function listItemsForVerticalMeridiem(amString, pmString) {
  return [{
    id: 'AM',
    value: amString
  }, {
    id: 'PM',
    value: pmString
  }];
};
var spinnerPropTypes = {
  position: PropTypes.arrayOf(PropTypes.number).isRequired,
  value: PropTypes.string,
  onChange: PropTypes.func,
  testId: PropTypes.string,
  style: PropTypes.objectOf(PropTypes.string),
  is24hours: PropTypes.bool,
  amString: PropTypes.string,
  pmString: PropTypes.string
};

/* istanbul ignore next */
var defaultSpinnerProps = {
  value: '',
  testId: 'time-picker-spinner',
  onChange: function onChange() {},
  style: {},
  is24hours: false,
  amString: 'AM',
  pmString: 'PM'
};
var TimePickerSpinner = /*#__PURE__*/React__default.forwardRef(function (_ref2, ref) {
  var onChange = _ref2.onChange,
    position = _ref2.position,
    value = _ref2.value,
    testId = _ref2.testId,
    style = _ref2.style,
    is24hours = _ref2.is24hours,
    amString = _ref2.amString,
    pmString = _ref2.pmString;
  var _useState15 = useState(null),
    _useState16 = _slicedToArray(_useState15, 2),
    container = _useState16[0],
    setContainer = _useState16[1];
  var currentTime = dayjs().format(AVAILABLE_FORMATS);
  var updatedStyle = useMemo(function () {
    var _style$zIndex;
    return _objectSpread(_objectSpread({}, style), {}, {
      '--zIndex': (_style$zIndex = style.zIndex) !== null && _style$zIndex !== void 0 ? _style$zIndex : 0
    });
  }, [style]);
  var firstVal = useMemo(function () {
    return is24hours ? timeUtils.get24Hours(value, currentTime) : timeUtils.get12Hours(value, currentTime);
  }, [value, is24hours, currentTime]);
  var secondVal = useMemo(function () {
    return timeUtils.getMinutes(value, currentTime);
  }, [value, currentTime]);
  var thirdVal = useMemo(function () {
    return is24hours ? '' : timeUtils.getMeridiem(value, currentTime, amString, pmString) === amString ? 'AM' : 'PM';
  }, [is24hours, value, currentTime, amString, pmString]);
  var _useState17 = useState([firstVal, secondVal, thirdVal]),
    _useState18 = _slicedToArray(_useState17, 2),
    selected = _useState18[0],
    setSelected = _useState18[1];
  var _useState19 = useState(value),
    _useState20 = _slicedToArray(_useState19, 2),
    callbackValue = _useState20[0],
    setCallbackValue = _useState20[1];
  var _useState21 = useState(0),
    _useState22 = _slicedToArray(_useState21, 2),
    setFocusedSpinner = _useState22[1];
  var secondSpinnerRef = useRef();
  var thirdSpinnerRef = useRef();
  var numberOfSpinners = is24hours ? 2 : 3;
  useEffect(function () {
    var active = document.activeElement; // currently focused element
    var nearestModal = active === null || active === void 0 ? void 0 : active.closest('.cds--modal');
    setContainer(nearestModal || document.body);
  }, []);
  useEffect(function () {
    setSelected([firstVal, secondVal, thirdVal]);
  }, [firstVal, secondVal, thirdVal]);
  useEffect(function () {
    onChange(callbackValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [callbackValue]);
  var handleOnClick = function handleOnClick(str, index) {
    setSelected(function (prev) {
      var arr = _toConsumableArray(prev);
      arr[index] = str;
      var newValue = is24hours ? "".concat(arr[0], ":").concat(arr[1]) : "".concat(arr[0], ":").concat(arr[1], " ").concat(arr[2]);
      setCallbackValue(newValue);
      return arr;
    });
  };

  /* eslint-disable no-unused-expressions */
  var handleRightArrowClick = useCallback(function () {
    setFocusedSpinner(function (prevValue) {
      var nextSelected = (prevValue + 1) % numberOfSpinners;
      if (nextSelected === 0) {
        ref === null || ref === void 0 || ref.current.focus();
      }
      if (nextSelected === 1) {
        secondSpinnerRef === null || secondSpinnerRef === void 0 || secondSpinnerRef.current.focus();
      }
      if (nextSelected === 2) {
        thirdSpinnerRef === null || thirdSpinnerRef === void 0 || thirdSpinnerRef.current.focus();
      }
      return nextSelected;
    });
  }, [numberOfSpinners, ref]);
  var handleLeftArrowClick = useCallback(function () {
    var stepBehind = is24hours ? 1 : 2;
    setFocusedSpinner(function (prevValue) {
      var nextSelected = (prevValue + stepBehind) % numberOfSpinners;
      if (nextSelected === 0) {
        ref === null || ref === void 0 || ref.current.focus();
      }
      if (nextSelected === 1) {
        secondSpinnerRef === null || secondSpinnerRef === void 0 || secondSpinnerRef.current.focus();
      }
      if (nextSelected === 2) {
        thirdSpinnerRef === null || thirdSpinnerRef === void 0 || thirdSpinnerRef.current.focus();
      }
      return nextSelected;
    });
  }, [is24hours, numberOfSpinners, ref]);
  /* eslint-enable no-unused-expressions */

  var listSpinner1 = useMemo(function () {
    return /*#__PURE__*/React__default.createElement(ListSpinner, {
      testId: "".concat(testId, "-list-spinner-1"),
      ref: ref,
      onClick: function onClick(e) {
        return handleOnClick(e, 0);
      },
      list: is24hours ? listItemsForVertical24Hours : listItemsForVertical12Hours,
      defaultSelectedId: selected[0],
      onRightArrowClick: handleRightArrowClick,
      onLeftArrowClick: handleLeftArrowClick
    });
  }, /* eslint-disable-next-line react-hooks/exhaustive-deps */
  [selected[0]]);
  var listSpinner2 = useMemo(function () {
    return /*#__PURE__*/React__default.createElement(ListSpinner, {
      testId: "".concat(testId, "-list-spinner-2"),
      ref: secondSpinnerRef,
      onClick: function onClick(e) {
        return handleOnClick(e, 1);
      },
      list: listItemsForVerticalMinutes,
      defaultSelectedId: selected[1],
      onRightArrowClick: handleRightArrowClick,
      onLeftArrowClick: handleLeftArrowClick
    });
  }, /* eslint-disable-next-line react-hooks/exhaustive-deps */
  [selected[1]]);
  var listSpinner3 = useMemo(function () {
    return /*#__PURE__*/React__default.createElement(ListSpinner, {
      testId: "".concat(testId, "-list-spinner-3"),
      ref: thirdSpinnerRef,
      className: classnames("".concat(iotPrefix, "--time-picker-spinner-last-list-spinner"), _defineProperty({}, "".concat(iotPrefix, "--time-picker-spinner-last-list-spinner--PM"), selected[2] === pmString)),
      onClick: function onClick(e) {
        return handleOnClick(e, 2);
      },
      list: listItemsForVerticalMeridiem(amString, pmString),
      defaultSelectedId: selected[2],
      onRightArrowClick: handleRightArrowClick,
      onLeftArrowClick: handleLeftArrowClick
    });
  }, /* eslint-disable-next-line react-hooks/exhaustive-deps */
  [selected[2]]);
  var dropdown = /*#__PURE__*/React__default.createElement("div", {
    ref: ref,
    "data-testid": testId,
    className: classnames("".concat(iotPrefix, "--time-picker-spinner"), _defineProperty({}, "".concat(iotPrefix, "--time-picker-spinner--24h"), is24hours)),
    style: _objectSpread(_objectSpread({}, updatedStyle), {}, {
      left: "".concat(position[0], "px"),
      top: "".concat(position[1], "px")
    })
  }, listSpinner1, listSpinner2, is24hours ? null : listSpinner3);
  if (!container) return null;
  return /*#__PURE__*/ReactDOM__default.createPortal(dropdown, container);
});
TimePickerSpinner.propTypes = spinnerPropTypes;
TimePickerSpinner.defaultProps = defaultSpinnerProps;
TimePickerDropdown.propTypes = propTypes;
TimePickerDropdown.defaultProps = defaultProps;
TimePickerDropdown.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TimePickerDropdown",
  "props": {
    "className": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hideLabel": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Specify whether the input labels to be visually hidden",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "value": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Specify the value for input",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "secondaryValue": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Specify the value for secondary input (range)",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hideSecondaryLabel": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Specify whether the secondary label to be visually hidden",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "type": {
      "defaultValue": {
        "value": "'single'",
        "computed": false
      },
      "description": "Input can be for a single time or a range - defaults to single",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'single'",
          "computed": false
        }, {
          "value": "'range'",
          "computed": false
        }]
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  invalidText: 'The time entered is invalid',\n  warnText: undefined,\n  timeIconText: 'Open time picker',\n  placeholderText: 'hh:mm XM',\n  placeholderText24h: 'HH:mm',\n  readOnlyBtnText: 'Read only',\n  amString: 'AM',\n  pmString: 'PM',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "labelText": {
            "name": "string",
            "description": "Label for input (will be first, if range type)",
            "required": true
          },
          "helperText": {
            "name": "string",
            "required": false
          },
          "secondaryLabelText": {
            "name": "string",
            "description": "Label for second input in range",
            "required": false
          },
          "secondaryHelperText": {
            "name": "string",
            "required": false
          },
          "invalidText": {
            "name": "string",
            "required": false
          },
          "warnText": {
            "name": "string",
            "required": false
          },
          "timeIconText": {
            "name": "string",
            "required": false
          },
          "placeholderText": {
            "name": "string",
            "required": false
          },
          "placeholderText24h": {
            "name": "string",
            "required": false
          },
          "amString": {
            "name": "string",
            "required": false
          },
          "pmString": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "size": {
      "defaultValue": {
        "value": "'md'",
        "computed": false
      },
      "description": "Size of input",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'sm'",
          "computed": false
        }, {
          "value": "'md'",
          "computed": false
        }, {
          "value": "'lg'",
          "computed": false
        }]
      },
      "required": false
    },
    "disabled": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Specify whether the control is currently disabled",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "readOnly": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Specify whether the control is currently read only",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "warn": {
      "defaultValue": {
        "value": "[false, false]",
        "computed": false
      },
      "description": "Specify whether the control is currently in warning state",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "bool"
        }
      },
      "required": false
    },
    "invalid": {
      "defaultValue": {
        "value": "[false, false]",
        "computed": false
      },
      "description": "Specify whether the control is currently in invalid state",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "bool"
        }
      },
      "required": false
    },
    "light": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Boolean to swap for light theme",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "Optional handler that is called whenever <input> is updated - will be called with new value as an argument",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'time-picker'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "style": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "objectOf",
        "value": {
          "name": "union",
          "value": [{
            "name": "string"
          }, {
            "name": "number"
          }]
        }
      },
      "required": false
    },
    "is24hours": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "id": {
      "description": "",
      "type": {
        "name": "string"
      },
      "required": true
    }
  }
};
var TimePickerDropdown$1 = TimePickerDropdown;
TimePickerSpinner.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TimePickerSpinner",
  "props": {
    "value": {
      "defaultValue": {
        "value": "''",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'time-picker-spinner'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "style": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "objectOf",
        "value": {
          "name": "string"
        }
      },
      "required": false
    },
    "is24hours": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "amString": {
      "defaultValue": {
        "value": "'AM'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "pmString": {
      "defaultValue": {
        "value": "'PM'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "position": {
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "number"
        }
      },
      "required": true
    }
  }
};

export { TimePickerSpinner, TimePickerDropdown$1 as default };
