import React, { useEffect, useState } from "react";
import { AgentAccess } from "config";
import { useProjectId } from "./lib/state";

export function Agent({ agent, compact }: { agent: AgentAccess; compact?: boolean }): React.ReactNode {
	const projectId = useProjectId();
	const [ok, setOk] = useState<boolean>(false);
	useEffect(() => {
		let timeout: NodeJS.Timeout | null = null;
		const check = async () => {
			const resp = await fetch(`/api/project/${projectId}/agent/${agent.agentName}/status`);
			if (resp.ok) {
				const status = (await resp.json()).status;
				if (200 <= status && status < 300) {
					setOk(true);
					return;
				}
			}
			timeout = setTimeout(check, 500);
		};
		check();
		return () => {
			if (timeout != null) {
				clearTimeout(timeout);
			}
		};
	}, [agent.agentName, agent.address, setOk, projectId]);
	if (!ok) {
		return <div>Agent {agent.agentName} is loading...</div>;
	}
	const address = `${agent.address}${compact ? "/m" : ""}`;
	return <iframe key={agent.name} src={address} title={agent.agentName} className="w-full h-full" />;
}
