import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/taggedTemplateLiteralLoose";

var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9;

import React, { useCallback, useEffect, useRef, useState } from 'react';
import styled, { css } from 'styled-components';
import { TextInput as Input, Loader } from '../../Common';
import { ScrollView } from '../ScrollView';
import { IconCheck, IconClose } from '../Icons';
import { isTouchDevice, getElementOffset, useGlobalLabels } from '@sentecacommerce-theme/lib';
export function Autosuggest(_ref) {
  var {
    options,
    updateOptions,
    onOptionSelect,
    isFetching,
    getValue,
    getLabel,
    minLength = 3,
    debounceDelay = 400,
    selectedOption = '',
    disabled = false,
    withRemoveIconWhenSelected = false,
    onRemove,
    label
  } = _ref;
  var [query, setQuery] = useState('');
  var [isLoading, setIsLoading] = useState(isFetching);
  var [isFocused, setIsFocused] = useState(false);
  var {
    commonMessages,
    errorMessages
  } = useGlobalLabels();
  var inputRef = useRef(null);

  var onChange = e => {
    setIsFocused(true);
    setQuery(e.target.value);
  };

  var hideInput = useCallback(() => {
    setIsFocused(false);
  }, []);

  var handleClick = value => e => {
    e.preventDefault();
    e.stopPropagation();
    onOptionSelect(value);
    setTimeout(() => {
      setQuery('');
    }, 600);
    hideInput();
  };

  var onFocus = () => {
    window.removeEventListener('click', hideInput);
    window.addEventListener('click', hideInput);
    if (!minLength) updateOptions('');

    if (inputRef.current && isTouchDevice()) {
      var data = getElementOffset(inputRef.current);
      window.scrollTo({
        top: data.top - 70
      });
    }

    setIsFocused(true);
  };

  useEffect(() => {
    return () => {
      window.removeEventListener('click', hideInput);
    };
  }, [hideInput]);
  useEffect(() => {
    if (query.length < minLength) return;

    if (!debounceDelay) {
      updateOptions(query);
      isLoading && setIsLoading(false);
      return;
    }

    setIsLoading(true);
    var timeout = setTimeout(() => {
      updateOptions(query);
      setIsLoading(false);
    }, debounceDelay);
    return () => {
      clearTimeout(timeout);
    };
  }, [query, minLength, debounceDelay]);
  /**
   * Select first option on "Enter" and "Tab" click
   */

  var handleKeyDown = e => {
    var isEnter = e.key === 'Enter';
    var isTab = e.key === 'Tab';

    if ((isEnter || isTab) && options.length) {
      isEnter && e.preventDefault();
      var target = e.target;
      target.blur();
      onOptionSelect(options[0]);
    }
  };

  var isValidQuery = minLength !== 0 ? query.length >= minLength : true;
  var isExpandable = !selectedOption || selectedOption && !withRemoveIconWhenSelected;
  var showLoader = (isLoading || isFetching) && isValidQuery;

  var getContainerHeight = () => {
    if (!isFocused || !isExpandable) {
      return 0;
    }

    if (isValidQuery && !showLoader && options.length) {
      return Math.min(options.length * 52.5, 405);
    }

    return 80;
  };

  var height = getContainerHeight() / 10 + "rem";

  var onBlur = () => {
    setTimeout(() => {
      hideInput();
    }, 50);
  };

  var handleRemove = e => {
    e == null ? void 0 : e.preventDefault();
    setQuery('');
    onRemove();
  };

  return /*#__PURE__*/React.createElement(Rel, null, /*#__PURE__*/React.createElement(Container, {
    isDisabled: disabled,
    isFocused: isFocused,
    onClick: e => e.stopPropagation()
  }, /*#__PURE__*/React.createElement(Input, {
    onChange: onChange,
    value: selectedOption || query,
    onFocus: onFocus,
    onBlur: onBlur,
    disabled: disabled,
    label: label,
    inputSize: "normal",
    inputRef: inputRef,
    onKeyDown: handleKeyDown
  }), /*#__PURE__*/React.createElement(OptionList, {
    isFocused: isFocused,
    style: {
      height
    }
  }, isValidQuery && !showLoader && /*#__PURE__*/React.createElement(ScrollView, {
    maxHeight: "40.5rem"
  }, /*#__PURE__*/React.createElement(React.Fragment, null, options.map(option => {
    var value = getValue(option);
    var optionLabel = getLabel(option);
    return /*#__PURE__*/React.createElement(Option, {
      onMouseDown: handleClick(option),
      key: "Option__" + value + "--" + optionLabel
    }, optionLabel);
  }))), isValidQuery && !showLoader && !options.length && /*#__PURE__*/React.createElement(Center, null, errorMessages.noResults), showLoader && /*#__PURE__*/React.createElement(Center, null, /*#__PURE__*/React.createElement(Loader, null)), !isValidQuery && /*#__PURE__*/React.createElement(Center, null, commonMessages.pleaseFill, " ", minLength, " ", commonMessages.symbols))), !isExpandable && /*#__PURE__*/React.createElement(RemoveIconContainer, {
    onClick: handleRemove
  }, /*#__PURE__*/React.createElement(IconClose, null), /*#__PURE__*/React.createElement(IconCheck, null)));
}
var Rel = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n  position: relative;\n"])));
var DefaultStyle = styled.li.attrs({
  className: 'py-2 px-3'
})(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n  display: flex;\n  text-align: left;\n  border-bottom: 0.1rem solid ", ";\n\n  &:last-child {\n    border-bottom: 0;\n  }\n"])), (_ref2) => {
  var {
    theme
  } = _ref2;
  return theme.palette.disabled;
});
var Option = styled(DefaultStyle)(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n  &:hover {\n    cursor: pointer;\n    background-color: ", ";\n  }\n"])), (_ref3) => {
  var {
    theme
  } = _ref3;
  return theme.palette.disabled;
});
var Center = styled(DefaultStyle)(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n"])));
var RemoveIconContainer = styled.button.attrs({
  type: 'button'
})(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n\n  display: flex !important;\n  border-radius: 0.5rem !important;\n  align-items: center;\n  justify-content: flex-end;\n  padding-right: 2rem;\n  z-index: 1000;\n\n  &:hover {\n    opacity: 1 !important;\n    background-color: rgba(34, 34, 34, 0.1);\n\n    & svg:first-child {\n      display: block;\n    }\n\n    & svg:last-child {\n      display: none;\n    }\n  }\n\n  & svg:last-child {\n    width: 1.5rem;\n    height: 1.5rem;\n    fill: ", ";\n  }\n\n  & svg:first-child {\n    display: none;\n    width: 1.3rem;\n    height: 1.3rem;\n    fill: ", ";\n  }\n"])), (_ref4) => {
  var {
    theme
  } = _ref4;
  return theme.palette.primary;
}, (_ref5) => {
  var {
    theme
  } = _ref5;
  return theme.palette.danger;
});
var Container = styled.div(_templateObject6 || (_templateObject6 = _taggedTemplateLiteralLoose(["\n  position: relative;\n\n  ", "\n\n  ", "\n"])), props => props.isDisabled && css(_templateObject7 || (_templateObject7 = _taggedTemplateLiteralLoose(["\n      &:after {\n        content: '';\n        display: block;\n        width: 100%;\n        height: 100%;\n        position: absolute;\n        top: 0;\n        left: 0;\n        z-index: 12;\n        background: rgba(34, 34, 34, 0.1);\n      }\n    "]))), props => props.isFocused && css(_templateObject8 || (_templateObject8 = _taggedTemplateLiteralLoose(["\n      & input {\n        border-color: ", " !important;\n      }\n    "])), (_ref6) => {
  var {
    theme
  } = _ref6;
  return theme.palette.hint;
}));
var OptionList = styled.ul(_templateObject9 || (_templateObject9 = _taggedTemplateLiteralLoose(["\n  height: 0;\n  overflow: hidden;\n  box-sizing: border-box;\n\n  background: ", ";\n  position: absolute;\n  top: 4.1rem;\n  width: 100%;\n  border: 0;\n  border: 0.1rem solid\n    ", ";\n  border-top: 0;\n  z-index: 100;\n  transition: ", ";\n"])), props => props.isFocused ? props.theme.palette.secondary : 'transparent', props => props.isFocused ? props.theme.palette.hint : 'transparent', props => props.isFocused ? 'height 0.2s ease' : 'height 0.2s ease, background 0s ease 0.1s, border 0s ease 0.1s');
//# sourceMappingURL=index.js.map