/**
 * Handles `/services/:type` (no instance id). Resolves the first enabled
 * instance and redirects. Shows an empty state if none are configured.
 */
import { useMemo } from "react";
import { Link, useParams, Navigate } from "react-router-dom";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useServiceInstances } from "../hooks/useServices";

export function ServiceTypePage() {
	const { serviceType = "" } = useParams<{ serviceType: string }>();
	const { data: instances = [], isLoading } = useServiceInstances(
		serviceType || undefined,
	);

	const firstEnabled = useMemo(
		() => instances.find((s) => s.enabled) ?? instances[0],
		[instances],
	);

	if (isLoading) {
		return (
			<div className="flex h-32 items-center justify-center">
				<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
			</div>
		);
	}

	if (firstEnabled) {
		return (
			<Navigate to={`/services/${serviceType}/${firstEnabled.id}`} replace />
		);
	}

	return (
		<Alert>
			<AlertDescription className="flex flex-col gap-3">
				<span>No {serviceType} service configured.</span>
				<Button asChild className="w-fit">
					<Link to="/services">Add a service</Link>
				</Button>
			</AlertDescription>
		</Alert>
	);
}
