"use client";
import { useState, useEffect, useCallback, useMemo } from "react";
import { useRequest } from "./request"; // Importing your API hook
import { KEYPAIR } from "@/types/interfaces";

const useFetchData = <T,>(
  apiType: string,
  params?: object,
  dependencies: unknown[] = []
) => {
  const { request, loading } = useRequest();
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      const response = await request(apiType, params as KEYPAIR | FormData);
      console.log("********", response)
      setData((response?.data as T) ?? null);
    } catch (err) {
      console.error(`Error fetching ${apiType}:`, err);
      setError("Failed to fetch data");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [apiType, JSON.stringify(params)]);

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, dependencies); // Refetch when dependencies change

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const isLoading = useMemo(() => loading[`${apiType}_LOADING`], [loading]);

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

export default useFetchData;
