import { useCallback, useEffect, useState } from "react";
import { normalizeApiError } from "../services/http.js";

export default function useQueryTable(fetcher, initialQuery = {}) {
  const [query, setQuery] = useState(initialQuery);
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const reload = useCallback(async (nextQuery) => {
    const q = nextQuery ?? query;
    setLoading(true);
    setError("");
    try {
      const data = await fetcher(q);
      setRows(Array.isArray(data) ? data : []);
      return data;
    } catch (err) {
      setError(normalizeApiError(err));
      setRows([]);
      return [];
    } finally {
      setLoading(false);
    }
  }, [fetcher, query]);

  useEffect(() => {
    reload();
  }, [reload]);

  return { rows, setRows, query, setQuery, loading, error, setError, reload };
}
