import axiosInstance from '@/utils/api-config';
import { getAxiosError } from '@/utils/errors-utils';
import { useEffect, useState } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const useGetApi = <T,>(url: string, params?: Record<string, any>) => {
  const [data, setData] = useState<T>();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ErrorState | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axiosInstance.get<T>(url, { params });
        setData(res.data);
        setError(null);
      } catch (err) {
        console.error(err);
        const message = getAxiosError(err);

        setError(message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url, params]);

  return { data, setData, loading, error };
};
