// 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 '@ui/components/Input';

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

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

const CustomSearchBox = ({ currentRefinement, isSearchStalled, refine }) => {
  const [query, setQuery] = useState('');
  const { initRequest } = useReadmeApi('https://metrics.readme.io');
  // delay to improve performance
  const onChange = debounce(value => refine(value), 300);

  const publishQueryToMetrics = search => {
    const readmeSubdomain = typeof window !== 'undefined' && 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,
          subdomain: readmeSubdomain.getAttribute('content'),
        }),
      });
    }
  };

  return (
    <div className={classes.SearchBox}>
      {/* eslint-disable jsx-a11y/no-autofocus */}
      <Input
        autoCapitalize="off"
        autoComplete="off"
        autoCorrect="off"
        autoFocus
        className={classes['SearchBox-Input']}
        onBlur={e => publishQueryToMetrics(e.currentTarget.value)}
        onChange={e => onChange(e.currentTarget.value)}
        spellCheck="false"
        tabIndex={0}
        type="search"
        value={currentRefinement}
      />
      {/* eslint-enable jsx-a11y/no-autofocus */}
      {!isSearchStalled && <i className={[classes['SearchBox-Search'], 'fa fa-search'].join(' ')} />}
      {isSearchStalled && <i className={classes['SearchBox-Spinner']} />}
    </div>
  );
};

const SearchBox = connectSearchBox(CustomSearchBox);

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

export default SearchBox;
