import { _ as _slicedToArray } from '../slicedToArray-BB-AwwkK.js';
import React__default, { useState, useEffect } from 'react';
import Input from '../input/index.js';
import usePrevious from '../use-previous/index.js';
import '../defineProperty-CEd-kZQW.js';
import '../extends-C4cduGrv.js';
import '../objectWithoutProperties-TXwlfNxG.js';
import 'classnames';

var isHex = function isHex(str) {
  return !isNaN(parseInt(str, 16)) || /^#/.test(str);
};

var remove = function remove(str, character) {
  return str && str.replace(character, "");
};

var prepend = function prepend(str, character) {
  return isHex(str) ? "".concat(character, str) : str;
};

var trim = function trim(str) {
  return str && str.trim().slice(0, 6);
};

var ColorPickerInputGroup = function ColorPickerInputGroup(_ref) {
  var onChange = _ref.onChange,
      color = _ref.color;

  var _useState = useState(remove(color, "#")),
      _useState2 = _slicedToArray(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      focused = _useState4[0],
      setFocused = _useState4[1];

  var prevValue = usePrevious(value);
  useEffect(function () {
    var strippedColor = remove(color, "#");

    if (prevValue !== strippedColor && !focused) {
      setValue(strippedColor);
    }
  }, [color, prevValue, focused]);

  var changeColor = function changeColor(newValue) {
    var value = trim(remove(newValue, "#"));
    var color = {
      hex: prepend(value, "#"),
      source: "hex"
    };
    setValue(value);
    onChange(color);
  };

  var handleChange = function handleChange(event) {
    changeColor(event.target.value);
  };

  var handleFocus = function handleFocus() {
    setFocused(true);
  };

  var handleBlur = function handleBlur() {
    setFocused(false);
  };

  var handlePaste = function handlePaste(event) {
    event.preventDefault();
    changeColor(event.clipboardData.getData("text"));
  };

  return /*#__PURE__*/React__default.createElement("div", {
    className: "flex flex-auto items-center"
  }, /*#__PURE__*/React__default.createElement(Input, {
    className: "text-base uppercase leading-6 text-gray-900 w-full border-none focus:outline-blue",
    prepend: isHex(value) && '#',
    style: {
      padding: "0"
    },
    name: "hex",
    value: value,
    onBlur: handleBlur,
    onChange: handleChange,
    onFocus: handleFocus,
    onPaste: handlePaste,
    maxLength: "6"
  }));
};

export { ColorPickerInputGroup as default };
