import { filterQueries } from './utils';
import * as cacheApi from '@/api/cache/query';
import type { ResponseQueries } from '@/api/cache/types';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useDebounce } from 'use-debounce';

export function useFilteredQueries() {
  const { data: queries } = useQuery({
    enabled: false,
    queryFn: ({ signal }) => signal && cacheApi.getQueries({ signal }),
    queryKey: ['admin', 'cache', 'queries'],
    refetchOnWindowFocus: false,
  });

  const [filteredQueries, setFilteredQueries] = useState<ResponseQueries | undefined>(queries);
  const [filterString, setFilterString] = useState('');
  const [debouncedFilterString] = useDebounce(filterString, 350);

  useEffect(() => {
    if (!debouncedFilterString) {
      setFilteredQueries(queries);
    }
    if (queries && debouncedFilterString) {
      setFilteredQueries(filterQueries(queries, debouncedFilterString));
    }
  }, [debouncedFilterString, queries]);

  return { filteredQueries, queries, setFilterString };
}
