"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import type { AxiosError } from "axios";

interface UseApiQueryOptions {
  enabled?: boolean;
  deps?: unknown[];
}

interface UseApiQueryResult<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export function useApiQuery<T>(
  queryFn: () => Promise<T>,
  options?: UseApiQueryOptions
): UseApiQueryResult<T> {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const queryFnRef = useRef(queryFn);
  queryFnRef.current = queryFn;

  const enabled = options?.enabled !== false;

  const fetchData = useCallback(async () => {
    if (!enabled) return;
    setLoading(true);
    setError(null);
    try {
      const result = await queryFnRef.current();
      setData(result);
    } catch (err) {
      const axiosError = err as AxiosError<{ message?: string }>;
      setError(
        axiosError.response?.data?.message ||
          axiosError.message ||
          "Une erreur est survenue"
      );
    } finally {
      setLoading(false);
    }
  }, [enabled]);

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [enabled, ...(options?.deps || [])]);

  return { data, loading, error, refetch: fetchData };
}
