import { connectSearchBox } from "react-instantsearch-dom";
import * as classNames from "classnames";
import * as styles from "./styles.module.scss";
import debounce from "lodash/debounce";
import React from "react";
import Search from "../../icons/Search";
import Spinner from "../../icons/Spinner";
import Text, { Size, Element } from "../Text";

interface IProps {
  className?: string;
  hasScrolled: boolean;
  isSearchStalled: boolean;
  refine: (string) => void;
  query?: string;
  setQuery: (string) => void;
}

const SearchBox = ({
  className,
  hasScrolled,
  isSearchStalled,
  refine,
  query,
  setQuery
}: IProps) => {
  const blockSubmit = e => {
    var key = e.charCode || e.keyCode || 0;
    if (key == 13) {
      e.preventDefault();
    }
  };

  const doRefine = e => {
    refine(e.target.value);
  };

  const debounceSearch = debounce(doRefine, 200);

  const onChange = e => {
    setQuery(e.target.value);
    e.persist();
    debounceSearch(e);
  };

  return (
    <React.Fragment>
      <form
        noValidate
        role="search"
        onKeyPress={e => blockSubmit(e)}
        className={classNames({
          [className]: !!className,
          [styles.form]: true,
          [styles.hasScrolled]: hasScrolled || query
        })}
      >
        <label
          htmlFor="searchInput"
          className={classNames({
            [styles.inputWrapper]: true
          })}
        >
          <i className={styles.searchIcon}>
            <Search />
          </i>
          <input
            className={classNames({
              [styles.input]: true,
              [styles.hasScrolled]: hasScrolled || query
            })}
            type="search"
            placeholder={`Cerca argomento, città, regione ...`}
            aria-label={`Cerca argomento, città, regione ...`}
            onChange={onChange}
            name="searchInput"
            value={query}
          />
        </label>
        <div
          className={classNames({
            [styles.loading]: true,
            [styles.active]: isSearchStalled
          })}
        >
          <Text
            className={styles.loadingText}
            element={Element.Small}
            size={Size.P2}
          >
            Ricerca in corso
          </Text>
          <i className={styles.loadingIcon}>
            <Spinner />
          </i>
        </div>
      </form>
    </React.Fragment>
  );
};

const CustomSearchBox = connectSearchBox(SearchBox);

export default CustomSearchBox;
