import {useState, useEffect, useCallback} from "react";
import { SearchResultsStore } from "searchResults/domain/searchStore";
import { changeSearchRequestUseCase } from "searchResults/useCases/changeSearchRequestUseCase";
import { searchUseCase } from "searchResults/useCases/searchUseCase";

function useSearchViewModel(store: SearchResultsStore) {
  const search = useCallback(
    function () {
      return searchUseCase({
        searchResults: store.searchResults,
        searchRequest: store.searchRequest,
        search: store.search,
      });
    },
    [store.searchRequest, store.search, store.searchResults]
  );

  const changeSearchRequest = useCallback(
    function (searchRequest: string) {
      return changeSearchRequestUseCase({
        searchRequest: searchRequest,
        changeSearchRequest: store.changeSearchRequest,
      });
    },
    [store.searchRequest, store.changeSearchRequest]
  );
  const [inputValue, setInputValue] = useState(store.searchRequest);

  const changeInputValue = (value: string) => {
    setInputValue(value);
    changeSearchRequest(value);
  };

  useEffect(() => {
    if (store.searchRequest !== "") {
      search();
    }
  }, [store.searchRequest]);

  return {
    searchResults: store.searchResults,
    currentSearchState: store.searchRequest,
    failure: store.failure,
    isLoading: store.isLoading,
    isFailed: store.isFailed,
    search,
    changeInputValue,
    inputValue,
  };
}
export { useSearchViewModel };
