import { Alert, AlertDescription } from "@/components/ui/alert";
import { useServiceInstances } from "../hooks/useServices";
import { resolveWidget } from "../integrations/registry";
import type { WidgetInstance } from "../types";
import { SectionCard } from "./SectionCard";

interface Props {
	widget: WidgetInstance;
}

export function WidgetInstanceCard({ widget }: Props) {
	const { data: services = [] } = useServiceInstances();
	const resolved = resolveWidget(widget, services);

	if (!resolved) {
		const label = widget.service_id
			? `Unknown widget: ${widget.widget_kind} (service-bound)`
			: `Unknown widget: ${widget.widget_kind} (built-in)`;
		return (
			<SectionCard title={widget.title}>
				<Alert>
					<AlertDescription>{label}</AlertDescription>
				</Alert>
			</SectionCard>
		);
	}

	const Component = resolved.component;
	return (
		<Component
			widget={widget}
			refreshIntervalMs={resolved.refreshIntervalMs}
			description={resolved.description}
		/>
	);
}
