import type { ReactNode } from "react";
import type { UseQueryResult } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { styles as shared } from "@/ui/styles";
import { styles } from "./styles";

/**
 * One panel's data, with the loading and error surfaces the fire-and-forget
 * route loaders leave to the page. A configuration page holds several
 * independent collections; each states its own condition instead of the whole
 * page waiting on the slowest request.
 */
export default function QueryPanel<T>({
	query,
	children,
}: {
	query: UseQueryResult<T, Error>;
	children: (data: T) => ReactNode;
}) {
	if (query.isPending) {
		return (
			<p role="status" {...stylex.props(styles.pending, shared.pulse)}>
				Loading…
			</p>
		);
	}
	if (query.isError) return <InlineError error={query.error} onRetry={() => void query.refetch()} />;
	return <>{children(query.data)}</>;
}
