// 3rd-party libs
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';
import { connectSearchBox } from 'react-instantsearch-dom';

// Components
import Input from '../../../../components/Input';

// Internals
import useReadmeApi from '../../../../../core/hooks/useReadmeApi';

// Style
import classes from './style.module.scss';

var CustomSearchBox = function CustomSearchBox(_ref) {
  var currentRefinement = _ref.currentRefinement,
      isSearchStalled = _ref.isSearchStalled,
      refine = _ref.refine;

  var _useState = useState(''),
      query = _useState[0],
      setQuery = _useState[1];

  var initRequest = useReadmeApi('https://metrics.readme.io')[2];
  // delay to improve performance
  var _onChange = debounce(function (value) {
    return refine(value);
  }, 300);

  var publishQueryToMetrics = function publishQueryToMetrics(search) {
    var readmeSubdomain = document.querySelector('meta[name=readme-subdomain]');

    if (readmeSubdomain && query !== search) {
      setQuery(search);
      initRequest({
        path: 'search',
        headers: { 'Content-Type': 'application/json' },
        method: 'POST',
        body: JSON.stringify({
          search: search,
          subdomain: readmeSubdomain.getAttribute('content')
        })
      });
    }
  };

  return React.createElement(
    'div',
    { className: classes.SearchBox },
    React.createElement(Input, {
      autoCapitalize: 'off',
      autoComplete: 'off',
      autoCorrect: 'off',
      autoFocus: true,
      className: classes['SearchBox-Input'],
      onBlur: function onBlur(e) {
        return publishQueryToMetrics(e.currentTarget.value);
      },
      onChange: function onChange(e) {
        return _onChange(e.currentTarget.value);
      },
      spellCheck: 'false',
      tabIndex: 0,
      type: 'search',
      value: currentRefinement
    }),
    !isSearchStalled && React.createElement('i', { className: [classes['SearchBox-Search'], 'fa fa-search'].join(' ') }),
    isSearchStalled && React.createElement('i', { className: classes['SearchBox-Spinner'] })
  );
};

var SearchBox = connectSearchBox(CustomSearchBox);

CustomSearchBox.propTypes = process.env.NODE_ENV !== "production" ? {
  currentRefinement: PropTypes.string,
  // Algolia says this should be boolean, but sometimes it’s undefined
  isSearchStalled: PropTypes.any,
  refine: PropTypes.func
} : {};

export default SearchBox;