"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StyledInputTimeWrapper = exports.InputTime = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _compromise = _interopRequireDefault(require("compromise"));
var _compromiseDates = _interopRequireDefault(require("compromise-dates"));
var _moment = _interopRequireDefault(require("moment"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _timeUtils = require("../../utils/timeUtils");
var _ComboBox = require("../ComboBox/ComboBox");
var _excluded = ["mode", "selected", "min", "max", "onChange", "step", "size", "className", "placeholder", "triggerMode", "disabled", "invalid"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
_compromise.default.plugin(_compromiseDates.default);
var StyledInputTimeWrapper = exports.StyledInputTimeWrapper = _styledComponents.default.div.withConfig({
  displayName: "InputTime__StyledInputTimeWrapper",
  componentId: "sc-71akdh-0"
})(["max-width:176px;flex:1;& .c-combo-box--list{min-width:176px;}"]);
var renderOption = function renderOption(option) {
  return /*#__PURE__*/_react.default.createElement("div", {
    id: option.id
  }, option.name);
};
var InputTime = exports.InputTime = function InputTime(_ref) {
  var _ref$mode = _ref.mode,
    mode = _ref$mode === void 0 ? "24" : _ref$mode,
    defaultSelected = _ref.selected,
    _ref$min = _ref.min,
    min = _ref$min === void 0 ? "00:00" : _ref$min,
    _ref$max = _ref.max,
    max = _ref$max === void 0 ? "23:45" : _ref$max,
    onChange = _ref.onChange,
    _ref$step = _ref.step,
    step = _ref$step === void 0 ? 15 : _ref$step,
    size = _ref.size,
    className = _ref.className,
    placeholder = _ref.placeholder,
    triggerMode = _ref.triggerMode,
    disabled = _ref.disabled,
    invalid = _ref.invalid,
    rest = _objectWithoutProperties(_ref, _excluded);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var generateTimeOptions = function generateTimeOptions() {
    var minTime = (0, _moment.default)((0, _timeUtils.isValidTime)(min) ? min : "00:00", "HH:mm");
    var maxTime = (0, _moment.default)((0, _timeUtils.isValidTime)(max) ? max : "23:45", "HH:mm");
    var allOptions = [];
    var currentTime = (0, _moment.default)("00:00", "HH:mm");
    while (currentTime.isBefore((0, _moment.default)("24:00", "HH:mm"))) {
      allOptions.push({
        id: currentTime.format("HH:mm"),
        name: currentTime.format(mode === "12" ? "hh:mm A" : "HH:mm")
      });
      currentTime.add(step, "minutes");
    }
    return allOptions.filter(function (option) {
      return (0, _moment.default)(option.id, "HH:mm").isSameOrAfter(minTime) && (0, _moment.default)(option.id, "HH:mm").isSameOrBefore(maxTime);
    });
  };
  var timeOptions = generateTimeOptions();
  var isValidDefaultSelected = defaultSelected ? timeOptions.some(function (opt) {
    return opt.id === defaultSelected;
  }) : false;
  var _useState3 = (0, _react.useState)(isValidDefaultSelected ? defaultSelected : undefined),
    _useState4 = _slicedToArray(_useState3, 2),
    selected = _useState4[0],
    setSelected = _useState4[1];
  var handleInputChange = (0, _react.useCallback)(function (text) {
    if (/\d{1,2}:\d{2}/.test(text.trim())) {
      return;
    }
    var doc = (0, _compromise.default)(text);
    var parsed = doc.times().get()[0];
    if (parsed && parsed["24h"] && parsed["24h"] !== selected) {
      var value = (0, _moment.default)(parsed).format("HH:mm");
      if (timeOptions.some(function (option) {
        return option.id === value;
      })) {
        setSelected(value);
        onChange === null || onChange === void 0 || onChange(value);
        setIsOpen(false);
      }
    }
  }, [onChange, selected, timeOptions]);
  var handleChange = function handleChange(e) {
    setSelected(e);
    onChange === null || onChange === void 0 || onChange(e);
  };
  var handleOpen = function handleOpen() {
    setIsOpen(true);
  };
  var handleClose = function handleClose() {
    setIsOpen(false);
  };
  (0, _react.useEffect)(function () {
    if (isOpen && selected) {
      var _document$getElementB;
      var selectedItem = (_document$getElementB = document.getElementById(selected)) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.parentElement;
      selectedItem === null || selectedItem === void 0 || selectedItem.scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    }
  }, [isOpen, selected]);
  (0, _react.useEffect)(function () {
    if (defaultSelected !== selected && timeOptions.some(function (opt) {
      return opt.id === defaultSelected;
    })) setSelected(defaultSelected);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultSelected, timeOptions]);
  return /*#__PURE__*/_react.default.createElement(StyledInputTimeWrapper, {
    className: (0, _classnames.default)("c-input-time", className)
  }, /*#__PURE__*/_react.default.createElement(_ComboBox.ComboBox, _extends({}, rest, {
    options: timeOptions,
    open: isOpen,
    disabledInternalSort: true,
    selected: selected,
    keepSameOptionsOrder: true,
    onInputChange: handleInputChange,
    onChange: handleChange,
    forceCloseMenu: true,
    placeholder: placeholder,
    renderOption: renderOption,
    autoHeightMax: 226,
    size: size,
    onClose: handleClose,
    onOpen: handleOpen,
    triggerMode: triggerMode,
    disabled: disabled,
    invalid: invalid
  })));
};
//# sourceMappingURL=InputTime.js.map