import { objectWithoutProperties as _objectWithoutProperties, slicedToArray as _slicedToArray, extends as _extends, defineProperty as _defineProperty, objectSpread2 as _objectSpread2 } from '../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useRef, useState, useEffect } from 'react';
import cls from 'classnames';
import { delimiter, processTimeInput } from './utils/index.js';
import { StyledInput, StyledTimePickerGrid, LeftHelper, base } from './TimePicker.styles.js';
import { classes } from './TimePicker.tokens.js';
import { FloatingPopover } from './FloatingPopover.js';
import { base as base$2 } from './variations/_size/base.js';
import { base as base$1 } from './variations/_view/base.js';
import { base as base$3 } from './variations/_hint-view/base.js';
import { base as base$4 } from './variations/_hint-size/base.js';
import { base as base$5 } from './variations/_disabled/base.js';
import { base as base$6 } from './variations/_readonly/base.js';
import { useKeyNavigation } from './hooks/useKeyboardNavigation.js';
import { useForkRef } from '../../hooks/useForkRef.js';
import { useOutsideClick } from '../../hooks/useOutsideClick.js';
import { getSizeValueFromProp } from '../../utils/getSizeValueFromProp.js';

var _excluded = ["className", "value", "opened", "view", "size", "disabled", "readonly", "stretched", "appearance", "hasClearDivider", "valueError", "valueSuccess", "valueEdited", "label", "labelPlacement", "keepPlaceholder", "required", "requiredPlacement", "hasRequiredIndicator", "placeholder", "leftHelper", "contentLeft", "contentRight", "textBefore", "textAfter", "autoComplete", "hintTrigger", "hintText", "hintView", "hintSize", "hintTargetIcon", "hintTargetPlacement", "hintPlacement", "hintHasArrow", "hintOffset", "hintWidth", "hintContentLeft", "frame", "usePortal", "placement", "closeOnOverlayClick", "closeOnEsc", "disableFlip", "offset", "zIndex", "dropdownAlign", "dropdownWidth", "dropdownHeight", "columnsQuantity", "min", "max", "multiplicityMinutes", "multiplicitySeconds", "onToggle", "onFocus", "onChange"];

// changes to start tests

var timePickerRoot = function timePickerRoot(Root) {
  return /*#__PURE__*/forwardRef(function (_ref, ref) {
    var className = _ref.className,
      outerValue = _ref.value,
      _ref$opened = _ref.opened,
      opened = _ref$opened === void 0 ? false : _ref$opened,
      view = _ref.view,
      size = _ref.size,
      _ref$disabled = _ref.disabled,
      disabled = _ref$disabled === void 0 ? false : _ref$disabled,
      _ref$readonly = _ref.readonly,
      readonly = _ref$readonly === void 0 ? false : _ref$readonly,
      stretched = _ref.stretched,
      appearance = _ref.appearance,
      hasClearDivider = _ref.hasClearDivider,
      valueError = _ref.valueError,
      valueSuccess = _ref.valueSuccess,
      valueEdited = _ref.valueEdited,
      label = _ref.label,
      _ref$labelPlacement = _ref.labelPlacement,
      labelPlacement = _ref$labelPlacement === void 0 ? 'outer' : _ref$labelPlacement,
      keepPlaceholder = _ref.keepPlaceholder,
      _ref$required = _ref.required,
      required = _ref$required === void 0 ? false : _ref$required,
      _ref$requiredPlacemen = _ref.requiredPlacement,
      requiredPlacement = _ref$requiredPlacemen === void 0 ? 'right' : _ref$requiredPlacemen,
      _ref$hasRequiredIndic = _ref.hasRequiredIndicator,
      hasRequiredIndicator = _ref$hasRequiredIndic === void 0 ? false : _ref$hasRequiredIndic,
      placeholder = _ref.placeholder,
      leftHelper = _ref.leftHelper,
      contentLeft = _ref.contentLeft,
      contentRight = _ref.contentRight,
      textBefore = _ref.textBefore,
      textAfter = _ref.textAfter,
      autoComplete = _ref.autoComplete,
      _ref$hintTrigger = _ref.hintTrigger,
      hintTrigger = _ref$hintTrigger === void 0 ? 'hover' : _ref$hintTrigger,
      hintText = _ref.hintText,
      _ref$hintView = _ref.hintView,
      hintView = _ref$hintView === void 0 ? 'default' : _ref$hintView,
      _ref$hintSize = _ref.hintSize,
      hintSize = _ref$hintSize === void 0 ? 'm' : _ref$hintSize,
      hintTargetIcon = _ref.hintTargetIcon,
      _ref$hintTargetPlacem = _ref.hintTargetPlacement,
      hintTargetPlacement = _ref$hintTargetPlacem === void 0 ? 'outer' : _ref$hintTargetPlacem,
      _ref$hintPlacement = _ref.hintPlacement,
      hintPlacement = _ref$hintPlacement === void 0 ? 'auto' : _ref$hintPlacement,
      hintHasArrow = _ref.hintHasArrow,
      _ref$hintOffset = _ref.hintOffset,
      hintOffset = _ref$hintOffset === void 0 ? [0, 0] : _ref$hintOffset,
      hintWidth = _ref.hintWidth,
      hintContentLeft = _ref.hintContentLeft,
      _ref$frame = _ref.frame,
      frame = _ref$frame === void 0 ? 'document' : _ref$frame,
      _ref$usePortal = _ref.usePortal,
      usePortal = _ref$usePortal === void 0 ? false : _ref$usePortal,
      _ref$placement = _ref.placement,
      placement = _ref$placement === void 0 ? 'bottom-start' : _ref$placement,
      _ref$closeOnOverlayCl = _ref.closeOnOverlayClick,
      closeOnOverlayClick = _ref$closeOnOverlayCl === void 0 ? true : _ref$closeOnOverlayCl,
      _ref$closeOnEsc = _ref.closeOnEsc,
      closeOnEsc = _ref$closeOnEsc === void 0 ? true : _ref$closeOnEsc,
      disableFlip = _ref.disableFlip,
      offset = _ref.offset,
      _ref$zIndex = _ref.zIndex,
      zIndex = _ref$zIndex === void 0 ? 1000 : _ref$zIndex,
      _ref$dropdownAlign = _ref.dropdownAlign,
      dropdownAlign = _ref$dropdownAlign === void 0 ? 'left' : _ref$dropdownAlign,
      dropdownWidth = _ref.dropdownWidth,
      dropdownHeight = _ref.dropdownHeight,
      _ref$columnsQuantity = _ref.columnsQuantity,
      columnsQuantity = _ref$columnsQuantity === void 0 ? 2 : _ref$columnsQuantity,
      min = _ref.min,
      max = _ref.max,
      multiplicityMinutes = _ref.multiplicityMinutes,
      multiplicitySeconds = _ref.multiplicitySeconds,
      onToggle = _ref.onToggle,
      onFocus = _ref.onFocus,
      onChange = _ref.onChange,
      rest = _objectWithoutProperties(_ref, _excluded);
    var inputRef = useRef(null);
    var timeGridRootRef = useRef(null);
    var floatingPopoverRef = useRef(null);
    var rootRef = useRef(null);
    var rootForkRef = useForkRef(rootRef, ref);
    var hoursHideTimeoutRef = useRef(null);
    var minutesHideTimeoutRef = useRef(null);
    var secondsHideTimeoutRef = useRef(null);
    var _useState = useState(opened),
      _useState2 = _slicedToArray(_useState, 2),
      isInnerOpen = _useState2[0],
      setIsInnerOpen = _useState2[1];
    var _useState3 = useState(outerValue || ''),
      _useState4 = _slicedToArray(_useState3, 2),
      innerTime = _useState4[0],
      setInnerTime = _useState4[1];
    var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      rootWidth = _useState6[0],
      setRootWidth = _useState6[1];
    var _useState7 = useState({
        hours: null,
        minutes: null,
        seconds: null,
        currentColumn: null
      }),
      _useState8 = _slicedToArray(_useState7, 2),
      setActiveTime = _useState8[1];
    var viewValue = outerValue !== null && outerValue !== void 0 ? outerValue : innerTime;
    var format = columnsQuantity === 3 ? 'HH:mm:ss' : 'HH:mm';
    var dropdownWidthValue = dropdownWidth ? getSizeValueFromProp(dropdownWidth, 'rem') : undefined;
    var dropdownHeightValue = dropdownHeight ? getSizeValueFromProp(dropdownHeight, 'rem') : undefined;
    useEffect(function () {
      return function () {
        [hoursHideTimeoutRef, minutesHideTimeoutRef, secondsHideTimeoutRef].forEach(function (timeoutRef) {
          if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
          }
        });
      };
    }, []);
    useEffect(function () {
      if (!viewValue) {
        return;
      }
      var timeString = viewValue;
      if (format === 'HH:mm' && viewValue.length > 5) {
        timeString = viewValue.substring(0, 5);
      }
      setInnerTime(viewValue);
      var _timeString$split$map = timeString.split(delimiter).map(Number),
        _timeString$split$map2 = _slicedToArray(_timeString$split$map, 3),
        hh = _timeString$split$map2[0],
        mm = _timeString$split$map2[1],
        ss = _timeString$split$map2[2];
      setActiveTime({
        hours: !Number.isNaN(hh) ? hh : null,
        minutes: !Number.isNaN(mm) ? mm : null,
        seconds: format === 'HH:mm:ss' && !Number.isNaN(ss) ? ss : null,
        currentColumn: null
      });
    }, [outerValue, format]);
    useEffect(function () {
      if (isInnerOpen && (disabled || readonly)) {
        setIsInnerOpen(false);
      }
    }, [disabled, readonly]);
    useEffect(function () {
      if (rootRef.current) {
        var width = rootRef.current.offsetWidth;
        setRootWidth(width);
      }
    }, [dropdownWidth, isInnerOpen]);
    var handleToggle = function handleToggle() {
      if (disabled || readonly) return;
      var newState = !isInnerOpen;
      setIsInnerOpen(newState);
      if (newState) {
        setActiveTime(function (prev) {
          return _objectSpread2(_objectSpread2({}, prev), {}, {
            currentColumn: 'hours'
          });
        });
      }
      onToggle === null || onToggle === void 0 || onToggle(newState);
    };
    useOutsideClick(function () {
      if (!isInnerOpen || !closeOnOverlayClick) {
        return;
      }
      setIsInnerOpen(false);
      onToggle === null || onToggle === void 0 || onToggle(false);
    }, [floatingPopoverRef, timeGridRootRef]);
    var handleOnChange = function handleOnChange(formattedValues) {
      var _timeString;
      if (!formattedValues) {
        return;
      }
      var timeString = formattedValues.value;
      if (format === 'HH:mm' && viewValue.length > 5) {
        timeString = viewValue.substring(0, 5);
      }
      setInnerTime((_timeString = timeString) !== null && _timeString !== void 0 ? _timeString : '');
      setActiveTime({
        hours: !Number.isNaN(formattedValues.timeValues.hour) ? formattedValues.timeValues.hour : null,
        minutes: !Number.isNaN(formattedValues.timeValues.minute) ? formattedValues.timeValues.minute : null,
        seconds: format === 'HH:mm:ss' && !Number.isNaN(formattedValues.timeValues.second) ? formattedValues.timeValues.second : null,
        currentColumn: null
      });
      if (onChange) {
        onChange(formattedValues, formattedValues);
      }
    };
    var handleInputChange = function handleInputChange(event) {
      var input = event.target.value;
      var cursorPos = event.target.selectionStart;
      var _processTimeInput = processTimeInput(input, format, cursorPos),
        innerString = _processTimeInput.innerString,
        values = _processTimeInput.values,
        newCursorPosition = _processTimeInput.newCursorPosition;
      var hours = values.hh,
        minutes = values.mm,
        seconds = values.ss;
      setInnerTime(innerString);
      setActiveTime(function (prev) {
        return _objectSpread2(_objectSpread2({}, prev), {}, {
          hours: hours,
          minutes: minutes,
          seconds: seconds
        });
      });
      var formattedValues = {
        value: innerString,
        timeValues: {
          hour: hours,
          minute: minutes,
          second: seconds
        }
      };
      if (onChange) {
        onChange(_objectSpread2(_objectSpread2({}, event), {}, {
          target: _objectSpread2(_objectSpread2({}, event.target), formattedValues)
        }), formattedValues);
      }
      requestAnimationFrame(function () {
        if (inputRef.current) {
          inputRef.current.setSelectionRange(newCursorPosition, newCursorPosition);
        }
      });
    };
    var handleKeyDown = function handleKeyDown(event) {
      if (event.key === 'Enter' && !isInnerOpen) {
        event.preventDefault();
        setIsInnerOpen(true);
        setActiveTime(function (prev) {
          return _objectSpread2(_objectSpread2({}, prev), {}, {
            currentColumn: 'hours'
          });
        });
        onToggle === null || onToggle === void 0 || onToggle(true);
      }
    };
    var handleOnKeyDown = function handleOnKeyDown(e) {
      onKeyDownNavigation(e);
      handleKeyDown(e);
    };
    var handleTimeGridRootClick = function handleTimeGridRootClick(event) {
      if (disabled || readonly) {
        return;
      }
      if (isInnerOpen && event.target === (timeGridRootRef === null || timeGridRootRef === void 0 ? void 0 : timeGridRootRef.current)) {
        setIsInnerOpen(false);
        if (onToggle) {
          onToggle(false, event);
        }
      }
    };
    var _useKeyNavigation = useKeyNavigation({
        isCalendarOpen: isInnerOpen,
        format: format,
        maskWithFormat: true,
        delimiter: delimiter,
        closeOnEsc: closeOnEsc,
        onToggle: handleToggle
      }),
      onKeyDownNavigation = _useKeyNavigation.onKeyDown;
    var getActualWidth = function getActualWidth() {
      var _String;
      if (!rootWidth) {
        return 'fit-content';
      }
      if (dropdownWidthValue === 'fixed' || dropdownWidthValue === undefined) {
        return undefined;
      }
      if (dropdownWidth === 'fullWidth') {
        return "".concat(rootWidth, "px");
      }
      if ((_String = String(dropdownWidth)) !== null && _String !== void 0 && _String.includes('%') && typeof dropdownWidth === 'string') {
        var widthValue = rootWidth / 100 * parseFloat(dropdownWidth.replace('%', ''));
        return "".concat(widthValue, "px");
      }
      return String(dropdownWidth || 'fit-content');
    };
    return /*#__PURE__*/React__default.createElement(Root, _extends({
      stretched: stretched,
      view: view,
      size: size,
      className: cls(classes.timePickerRoot, className, _defineProperty({}, classes.timePickerstretched, stretched)),
      disabled: disabled,
      readonly: readonly,
      ref: rootForkRef
    }, hintText && {
      hintView: hintView,
      hintSize: hintSize
    }, rest), /*#__PURE__*/React__default.createElement(FloatingPopover, {
      ref: floatingPopoverRef,
      opened: isInnerOpen,
      onToggle: handleToggle,
      offset: offset,
      placement: placement,
      disableFlip: disableFlip,
      portal: usePortal ? frame : undefined,
      zIndex: zIndex,
      target: function target(referenceRef) {
        return /*#__PURE__*/React__default.createElement(StyledInput, _extends({
          ref: inputRef,
          inputWrapperRef: referenceRef,
          className: cls(_defineProperty(_defineProperty(_defineProperty({}, classes.timePickerError, valueError), classes.timePickerSuccess, valueSuccess), classes.timePickerEdited, valueEdited)),
          value: viewValue,
          size: size,
          disabled: disabled,
          readOnly: readonly,
          appearance: appearance,
          hasDivider: appearance === 'clear' && hasClearDivider,
          placeholder: placeholder,
          contentLeft: contentLeft,
          contentRight: contentRight,
          textBefore: textBefore,
          textAfter: textAfter,
          autoComplete: autoComplete,
          onChange: handleInputChange,
          onFocus: onFocus,
          onKeyDown: handleOnKeyDown,
          required: required,
          requiredPlacement: requiredPlacement,
          hasRequiredIndicator: hasRequiredIndicator,
          label: label,
          labelPlacement: labelPlacement,
          keepPlaceholder: keepPlaceholder
        }, hintText ? {
          hintText: hintText,
          hintView: hintView,
          hintSize: hintSize,
          hintTrigger: hintTrigger,
          hintTargetIcon: hintTargetIcon,
          hintPlacement: hintPlacement,
          hintHasArrow: hintHasArrow,
          hintOffset: hintOffset,
          hintWidth: hintWidth,
          hintContentLeft: hintContentLeft,
          hintTargetPlacement: hintTargetPlacement
        } : {
          hintText: undefined
        }));
      }
    }, /*#__PURE__*/React__default.createElement(Root, {
      ref: timeGridRootRef,
      stretched: stretched,
      view: view,
      size: size,
      className: cls(classes.timePickerGridRoot, className, _defineProperty(_defineProperty(_defineProperty({}, classes.timePickerPlacementRight, dropdownAlign === 'right'), classes.timePickerFullWidth, dropdownWidth === 'fullWidth'), classes.timePickerFixed, dropdownWidth !== 'fullWidth')),
      disabled: disabled,
      readonly: readonly,
      onClick: handleTimeGridRootClick
    }, /*#__PURE__*/React__default.createElement(StyledTimePickerGrid, {
      view: view,
      size: size,
      format: format,
      columns: columnsQuantity,
      innerWidth: getActualWidth(),
      innerHeight: dropdownHeightValue,
      dropdownHeight: "100%",
      dropdownWidth: "fullWidth",
      value: viewValue,
      onChange: handleOnChange,
      disabled: disabled,
      min: min,
      max: max,
      multiplicityMinutes: multiplicityMinutes,
      multiplicitySeconds: multiplicitySeconds
    }))), leftHelper && /*#__PURE__*/React__default.createElement(LeftHelper, {
      className: cls(_defineProperty(_defineProperty(_defineProperty({}, classes.timePickerError, valueError), classes.timePickerSuccess, valueSuccess), classes.timePickerEdited, valueEdited))
    }, leftHelper));
  });
};
var timePickerConfig = {
  name: 'TimePicker',
  tag: 'div',
  layout: timePickerRoot,
  base: base,
  variations: {
    view: {
      css: base$1
    },
    size: {
      css: base$2
    },
    hintView: {
      css: base$3
    },
    hintSize: {
      css: base$4
    },
    disabled: {
      css: base$5,
      attrs: true
    },
    readonly: {
      css: base$6,
      attrs: true
    }
  },
  defaults: {
    size: 'm',
    view: 'default'
  }
};

export { timePickerConfig, timePickerRoot };
