import { useMemo, useState } from "react";
import { useEnv, useLeadAgent } from "@/lib/state";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Button } from "./ui/button";
import { RefreshCw } from "lucide-react";
import { Agent } from "@/Agent";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";

export function Preview() {
	const leadAgent = useLeadAgent();
	if (leadAgent == null) {
		return <PreviewImpl />;
	}
	return (
		<ResizablePanelGroup direction="horizontal" className="h-full">
			<ResizablePanel defaultSize={25}>
				<div className="p-4 h-full">
					{leadAgent ? <Agent agent={leadAgent} compact={true} /> : <div>No agent available</div>}
				</div>
			</ResizablePanel>
			<ResizableHandle withHandle />
			<ResizablePanel>
				<PreviewImpl />
			</ResizablePanel>
		</ResizablePanelGroup>
	);
}

function PreviewImpl() {
	const env = useEnv();
	const httpsAccess = useMemo(() => env.access.filter((a) => a.type === "https"), [env]);
	const [selectedUrl, setSelectedUrl] = useState<string | null>(null);
	const [refreshKey, setRefreshKey] = useState(0);
	return (
		<div className="w-full h-full flex flex-col">
			<div className="p-4 border-b flex items-center gap-2">
				<Select onValueChange={setSelectedUrl}>
					<SelectTrigger className="w-[300px]">
						<SelectValue placeholder="Select a gateway" />
					</SelectTrigger>
					<SelectContent>
						{httpsAccess.map((a) => (
							<SelectItem key={a.address} value={a.address}>
								{a.address}
							</SelectItem>
						))}
					</SelectContent>
				</Select>
				<Button variant="outline" size="icon" onClick={() => setRefreshKey((prev) => prev + 1)}>
					<RefreshCw className="h-4 w-4" />
				</Button>
			</div>
			<div className="flex-1">
				{selectedUrl ? (
					<iframe key={refreshKey} src={selectedUrl} className="w-full h-full border-0" />
				) : (
					<div className="flex items-center justify-center h-full">
						<p>Select a gateway to preview</p>
					</div>
				)}
			</div>
		</div>
	);
}
