import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setSearchString } from "../../store/actions/filters/filtersActions";
import { selectSearchString } from "../../store/selectors/filtersSelectors";

const useSearch = (applyAllFilters) => {
  const [searchStringLocally, setSearchStringLocally] = useState("");
  const [isInitallyLoaded, setIsInitiallyLoaded] = useState(false);
  const dispatch = useDispatch();
  const searchString = useSelector(selectSearchString);

  // On every global change of search string, new request to backend should be sent
  useEffect(() => {
    if (searchStringLocally !== searchString && applyAllFilters) {
      setSearchStringLocally(searchString);
    }
    if (isInitallyLoaded) {
      if (applyAllFilters) applyAllFilters();
    }
  }, [searchString]);

  // On every local change of search string, global state of search string should be also updated
  useEffect(() => {
    if (isInitallyLoaded && applyAllFilters) {
      dispatch(setSearchString(searchStringLocally));
    }
  }, [searchStringLocally]);

  const searchOffers = (searchValue) => {
    setIsInitiallyLoaded(true);
    setSearchStringLocally(searchValue);
  };

  const clear = () => {
    setSearchStringLocally("");
  };

  return {
    searchOffers,
    setSearchStringLocally,
    searchStringLocally,
    searchString,
    clear,
  };
};
export default useSearch;
