import React, { useEffect, useRef, useCallback } from "react";
import { connect } from "react-redux";
import { Search } from "semantic-ui-react";
import { getProductsByName } from "../actions";
import { getSearch } from "../reducers";
import { startSearch, cleanQuery, finishSearch, updateSelection } from "../search-actions";


function ItemInputFormSearch({onChange, search, getProductsByName, startSearch, cleanQuery, finishSearch, updateSelection }) {
  
  const { loading, results, value } = search;
  const timeoutRef = useRef<any>();

  const handleSearchChange = useCallback((e, data) => {
    clearTimeout(timeoutRef.current);
    startSearch(data);

    timeoutRef.current = setTimeout(async () => {
      if (data.value.length === 0) {
        cleanQuery()
        return;
      }

      let res = await getProductsByName(data.value);
        finishSearch(res);
       
    }, 300);
  }, [getProductsByName, startSearch, cleanQuery, finishSearch]);

  useEffect(() => {
    return () => {
      clearTimeout(timeoutRef.current);
    };
  }, []);

  const resultRenderer = ({ title }) => <span>{title}</span>;

  return (
    <Search
      id="search-input"
      input={{ fluid: true }}
      style={{ borderRadius: "0px !important" }}
      loading={loading}
      onResultSelect={(e, data) => {
          onChange(data.result);
          updateSelection(data);
      }}
      onSearchChange={handleSearchChange}
      resultRenderer={resultRenderer}
      noResultsMessage="Nichts gefunden..."
      placeholder="Lebensmittel"
      results={results}
      value={value}
    />
  );
}


const mapStateToProps = (state) => {
  return {
    search: getSearch(state)
  }
}

const mapDispatchToProps = {
  getProductsByName,
  startSearch, 
  cleanQuery, 
  finishSearch, 
  updateSelection
};

export default connect(mapStateToProps, mapDispatchToProps)(ItemInputFormSearch);

