import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useDebounce } from '@northern.tech/utils/debouncehook';
import { AppDispatch } from '../store';

interface UseAutocompleteFieldOptions<T = string[]> {
  query: string;
  fetchThunk: (params: { query: string }) => any;
  parseResponse?: (payload: any) => T;
  debounceMs?: number;
}

export function useAutocompleteField<T = string[]>({
  query,
  fetchThunk,
  parseResponse = (payload) => (Array.isArray(payload) ? payload : []) as T,
  debounceMs = 400
}: UseAutocompleteFieldOptions<T>) {
  const dispatch = useDispatch<AppDispatch>();
  const [options, setOptions] = useState<T>([] as T);
  const [loading, setLoading] = useState<boolean>(false);
  const debouncedQuery = useDebounce(query, debounceMs);

  useEffect(() => {
    if (!debouncedQuery || debouncedQuery.length < 1) {
      setOptions([] as T);
      return;
    }

    const fetchData = async () => {
      setLoading(true);
      try {
        const result = await dispatch(fetchThunk({ query: debouncedQuery }));
        if (result.payload) {
          const parsedOptions = parseResponse(result.payload);
          setOptions(parsedOptions);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedQuery]);

  return {
    options,
    loading
  };
}
