import { useCallback, useEffect, useState } from "react";

const EMPTY_PAGE = { items: [], page: 1, pageSize: 20, total: 0 };

export function usePagedResource(loader) {
  const [data, setData] = useState(EMPTY_PAGE);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [version, setVersion] = useState(0);

  const reload = useCallback(() => setVersion((current) => current + 1), []);

  useEffect(() => {
    let active = true;
    setLoading(true);
    setError(null);
    // Start inside the promise chain so synchronous validation errors use the same visible error state as network failures.
    Promise.resolve()
      .then(loader)
      .then((result) => {
        if (active) {
          setData(result || EMPTY_PAGE);
        }
      })
      .catch((requestError) => {
        if (active) {
          // Keep the structured error so the rendering locale, not the backend message language, determines what users see.
          setError(requestError);
        }
      })
      .finally(() => {
        if (active) {
          setLoading(false);
        }
      });
    return () => {
      active = false;
    };
  }, [loader, version]);

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