import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _extends from "@babel/runtime/helpers/esm/extends";
import _JSXStyle from "../styled-jsx.es.js";
/* "use client" */

import Fuse from 'fuse.js';
import React, { useEffect, useState } from 'react';
import { defaultFuseOptions } from '../config/config'; // defaultTheme
import { debounce } from '../utils/utils';
import Results from './Results';
import SearchInput from './SearchInput';
export var DEFAULT_INPUT_DEBOUNCE = 200;
export var MAX_RESULTS = 10;
export default function ReactSearchAutocomplete(_ref) {
  var _ref$items = _ref.items,
    items = _ref$items === void 0 ? [] : _ref$items,
    _ref$fuseOptions = _ref.fuseOptions,
    fuseOptions = _ref$fuseOptions === void 0 ? defaultFuseOptions : _ref$fuseOptions,
    _ref$inputDebounce = _ref.inputDebounce,
    inputDebounce = _ref$inputDebounce === void 0 ? DEFAULT_INPUT_DEBOUNCE : _ref$inputDebounce,
    _ref$onSearch = _ref.onSearch,
    onSearch = _ref$onSearch === void 0 ? function () {} : _ref$onSearch,
    _ref$onHover = _ref.onHover,
    onHover = _ref$onHover === void 0 ? function () {} : _ref$onHover,
    _ref$onSelect = _ref.onSelect,
    onSelect = _ref$onSelect === void 0 ? function () {} : _ref$onSelect,
    _ref$onFocus = _ref.onFocus,
    onFocus = _ref$onFocus === void 0 ? function () {} : _ref$onFocus,
    _ref$onClear = _ref.onClear,
    onClear = _ref$onClear === void 0 ? function () {} : _ref$onClear,
    _ref$showIcon = _ref.showIcon,
    showIcon = _ref$showIcon === void 0 ? true : _ref$showIcon,
    _ref$showClear = _ref.showClear,
    showClear = _ref$showClear === void 0 ? true : _ref$showClear,
    _ref$maxResults = _ref.maxResults,
    maxResults = _ref$maxResults === void 0 ? MAX_RESULTS : _ref$maxResults,
    _ref$placeholder = _ref.placeholder,
    placeholder = _ref$placeholder === void 0 ? '' : _ref$placeholder,
    _ref$autoFocus = _ref.autoFocus,
    autoFocus = _ref$autoFocus === void 0 ? false : _ref$autoFocus,
    _ref$resultStringKeyN = _ref.resultStringKeyName,
    resultStringKeyName = _ref$resultStringKeyN === void 0 ? 'name' : _ref$resultStringKeyN,
    _ref$inputSearchStrin = _ref.inputSearchString,
    inputSearchString = _ref$inputSearchStrin === void 0 ? '' : _ref$inputSearchStrin,
    formatResult = _ref.formatResult,
    _ref$showNoResults = _ref.showNoResults,
    showNoResults = _ref$showNoResults === void 0 ? true : _ref$showNoResults,
    _ref$showNoResultsTex = _ref.showNoResultsText,
    showNoResultsText = _ref$showNoResultsTex === void 0 ? 'No results' : _ref$showNoResultsTex,
    _ref$showItemsOnFocus = _ref.showItemsOnFocus,
    showItemsOnFocus = _ref$showItemsOnFocus === void 0 ? false : _ref$showItemsOnFocus,
    _ref$maxLength = _ref.maxLength,
    maxLength = _ref$maxLength === void 0 ? 0 : _ref$maxLength;
  // const theme = { ...defaultTheme, ...styling }
  var options = _extends({}, defaultFuseOptions, fuseOptions);
  var fuse = new Fuse(items, options);
  fuse.setCollection(items);
  var _useState = useState(inputSearchString),
    _useState2 = _slicedToArray(_useState, 2),
    searchString = _useState2[0],
    setSearchString = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    results = _useState4[0],
    setResults = _useState4[1];
  var _useState5 = useState(-1),
    _useState6 = _slicedToArray(_useState5, 2),
    highlightedItem = _useState6[0],
    setHighlightedItem = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    isSearchComplete = _useState8[0],
    setIsSearchComplete = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isTyping = _useState10[0],
    setIsTyping = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    showNoResultsFlag = _useState12[0],
    setShowNoResultsFlag = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    hasFocus = _useState14[0],
    setHasFocus = _useState14[1];
  useEffect(function () {
    setSearchString(inputSearchString);
    var timeoutId = setTimeout(function () {
      return setResults(fuseResults(inputSearchString));
    }, 0);
    return function () {
      return clearTimeout(timeoutId);
    };
  }, [inputSearchString]);
  useEffect(function () {
    (searchString === null || searchString === void 0 ? void 0 : searchString.length) > 0 && results && (results === null || results === void 0 ? void 0 : results.length) > 0 && setResults(fuseResults(searchString));
  }, [items]);
  useEffect(function () {
    if (showNoResults && searchString.length > 0 && !isTyping && results.length === 0 && !isSearchComplete) {
      setShowNoResultsFlag(true);
    } else {
      setShowNoResultsFlag(false);
    }
  }, [isTyping, showNoResults, isSearchComplete, searchString, results]);
  useEffect(function () {
    if (showItemsOnFocus && results.length === 0 && searchString.length === 0 && hasFocus) {
      setResults(items.slice(0, maxResults));
    }
  }, [showItemsOnFocus, results, searchString, hasFocus]);
  useEffect(function () {
    var handleDocumentClick = function handleDocumentClick() {
      eraseResults();
      setHasFocus(false);
    };
    document.addEventListener('click', handleDocumentClick);
    return function () {
      return document.removeEventListener('click', handleDocumentClick);
    };
  }, []);
  var handleOnFocus = function handleOnFocus(event) {
    onFocus(event);
    setHasFocus(true);
  };
  var callOnSearch = function callOnSearch(keyword) {
    var newResults = [];
    (keyword === null || keyword === void 0 ? void 0 : keyword.length) > 0 && (newResults = fuseResults(keyword));
    setResults(newResults);
    onSearch(keyword, newResults);
    setIsTyping(false);
  };
  var handleOnSearch = React.useCallback(inputDebounce > 0 ? debounce(function (keyword) {
    return callOnSearch(keyword);
  }, inputDebounce) : function (keyword) {
    return callOnSearch(keyword);
  }, [items]);
  var handleOnClick = function handleOnClick(result) {
    eraseResults();
    onSelect(result);
    setSearchString(result[resultStringKeyName]);
    setHighlightedItem(0);
  };
  var fuseResults = function fuseResults(keyword) {
    return fuse.search(keyword, {
      limit: maxResults
    }).map(function (result) {
      return _extends({}, result.item);
    }).slice(0, maxResults);
  };
  var handleSetSearchString = function handleSetSearchString(_ref2) {
    var target = _ref2.target;
    var keyword = target.value;
    setSearchString(keyword);
    handleOnSearch(keyword);
    setIsTyping(true);
    if (isSearchComplete) {
      setIsSearchComplete(false);
    }
  };
  var eraseResults = function eraseResults() {
    setResults([]);
    setIsSearchComplete(true);
  };
  var handleSetHighlightedItem = function handleSetHighlightedItem(_ref3) {
    var index = _ref3.index,
      event = _ref3.event;
    var itemIndex = -1;
    var setValues = function setValues(index) {
      setHighlightedItem(index);
      (results === null || results === void 0 ? void 0 : results[index]) && onHover(results[index]);
    };
    if (index !== undefined) {
      setHighlightedItem(index);
      (results === null || results === void 0 ? void 0 : results[index]) && onHover(results[index]);
    } else if (event) {
      switch (event.key) {
        case 'Enter':
          if (results.length > 0 && results[highlightedItem]) {
            event.preventDefault();
            onSelect(results[highlightedItem]);
            setSearchString(results[highlightedItem][resultStringKeyName]);
            onSearch(results[highlightedItem][resultStringKeyName], results);
          } else {
            onSearch(searchString, results);
          }
          setHighlightedItem(-1);
          eraseResults();
          break;
        case 'ArrowUp':
          event.preventDefault();
          itemIndex = highlightedItem > -1 ? highlightedItem - 1 : results.length - 1;
          setValues(itemIndex);
          break;
        case 'ArrowDown':
          event.preventDefault();
          itemIndex = highlightedItem < results.length - 1 ? highlightedItem + 1 : -1;
          setValues(itemIndex);
          break;
        default:
          break;
      }
    }
  };
  return /*#__PURE__*/React.createElement("div", {
    className: _JSXStyle.dynamic([["3512916558", [function (props) {
      return parseInt(props.theme.height) + 2 + 'px';
    }, function (props) {
      return props.theme.border;
    }, function (props) {
      return props.theme.borderRadius;
    }, function (props) {
      return props.theme.backgroundColor;
    }, function (props) {
      return props.theme.color;
    }, function (props) {
      return props.theme.fontSize;
    }, function (props) {
      return props.theme.fontFamily;
    }, function (props) {
      return props.theme.zIndex;
    }, function (props) {
      return props.theme.boxShadow;
    }, function (props) {
      return props.theme.boxShadow;
    }, function (props) {
      return props.theme.boxShadow;
    }]]]) + " " + "search-bar-wrapper"
  }, /*#__PURE__*/React.createElement(SearchInput, {
    searchString: searchString,
    setSearchString: handleSetSearchString,
    eraseResults: eraseResults,
    autoFocus: autoFocus,
    onFocus: handleOnFocus,
    onClear: onClear,
    placeholder: placeholder,
    showIcon: showIcon,
    showClear: showClear,
    setHighlightedItem: handleSetHighlightedItem,
    maxLength: maxLength
  }), /*#__PURE__*/React.createElement(Results, {
    results: results,
    onClick: handleOnClick,
    setSearchString: setSearchString,
    showIcon: showIcon,
    maxResults: maxResults,
    resultStringKeyName: resultStringKeyName,
    formatResult: formatResult,
    highlightedItem: highlightedItem,
    setHighlightedItem: handleSetHighlightedItem,
    showNoResultsFlag: showNoResultsFlag,
    showNoResultsText: showNoResultsText
  }), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "3512916558",
    dynamic: [function (props) {
      return parseInt(props.theme.height) + 2 + 'px';
    }, function (props) {
      return props.theme.border;
    }, function (props) {
      return props.theme.borderRadius;
    }, function (props) {
      return props.theme.backgroundColor;
    }, function (props) {
      return props.theme.color;
    }, function (props) {
      return props.theme.fontSize;
    }, function (props) {
      return props.theme.fontFamily;
    }, function (props) {
      return props.theme.zIndex;
    }, function (props) {
      return props.theme.boxShadow;
    }, function (props) {
      return props.theme.boxShadow;
    }, function (props) {
      return props.theme.boxShadow;
    }]
  }, ".__jsx-style-dynamic-selector{position:relative;height:".concat(function (props) {
    return parseInt(props.theme.height) + 2 + 'px';
  }, ";}.search-bar-wrapper.__jsx-style-dynamic-selector{position:absolute;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;width:100%;border:").concat(function (props) {
    return props.theme.border;
  }, ";border-radius:").concat(function (props) {
    return props.theme.borderRadius;
  }, ";background-color:").concat(function (props) {
    return props.theme.backgroundColor;
  }, ";color:").concat(function (props) {
    return props.theme.color;
  }, ";font-size:").concat(function (props) {
    return props.theme.fontSize;
  }, ";font-family:").concat(function (props) {
    return props.theme.fontFamily;
  }, ";z-index:").concat(function (props) {
    return props.theme.zIndex;
  }, ";}.search-bar-wrapper.__jsx-style-dynamic-selector:hover{box-shadow:").concat(function (props) {
    return props.theme.boxShadow;
  }, ";}.search-bar-wrapper.__jsx-style-dynamic-selector:active{box-shadow:").concat(function (props) {
    return props.theme.boxShadow;
  }, ";}.search-bar-wrapper.__jsx-style-dynamic-selector:focus-within{box-shadow:").concat(function (props) {
    return props.theme.boxShadow;
  }, ";}")));
}