/**
 * Configurable per-service Overview tab.
 *
 * Each service instance manages its own set of widgets on this tab. The
 * widget system is reused from the main Dashboard: widget instances with
 * a `service_id` matching this instance are fetched and rendered in a
 * responsive grid. An edit button opens the WidgetConfigDialog (same one
 * the Dashboard uses) for add/remove/reorder/enable/disable.
 */
import { useMemo, useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Settings2 } from "lucide-react";
import { useWidgetInstances } from "../../hooks/useWidgets";
import { WidgetInstanceCard } from "../../components/WidgetInstance";
import { WidgetConfigDialog } from "../../components/WidgetConfigDialog";
import type { ServiceInstance } from "../../types";

export function OverviewTab({ instance }: { instance: ServiceInstance }) {
	const { data: widgets = [] } = useWidgetInstances(instance.id);
	const [configOpen, setConfigOpen] = useState(false);
	const [editWidgetId, setEditWidgetId] = useState<string | undefined>();

	const visibleWidgets = useMemo(
		() =>
			widgets
				.filter((w) => w.enabled)
				.sort((a, b) => a.sort_order - b.sort_order),
		[widgets],
	);

	return (
		<div className="flex flex-col gap-4">
			<div className="flex items-center justify-between">
				<h3 className="text-sm font-semibold text-muted-foreground">
					{instance.name} overview
				</h3>
				<Button
					variant="outline"
					size="sm"
					className="mobile-touch-target"
					onClick={() => setConfigOpen(true)}
				>
					<Settings2 className="size-4" />
					Edit widgets
				</Button>
			</div>

			{visibleWidgets.length > 0 ? (
				<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
					{visibleWidgets.map((widget) => (
						<WidgetInstanceCard
							key={widget.id}
							widget={widget}
							onEdit={(id) => {
								setEditWidgetId(id);
								setConfigOpen(true);
							}}
						/>
					))}
				</div>
			) : (
				<Alert>
					<AlertDescription className="flex flex-col gap-3">
						<span>
							No widgets on this overview yet. Add widgets to show key metrics
							and information for {instance.name}.
						</span>
						<Button
							size="sm"
							className="w-fit mobile-touch-target"
							onClick={() => setConfigOpen(true)}
						>
							Add widgets
						</Button>
					</AlertDescription>
				</Alert>
			)}

			<WidgetConfigDialog
				open={configOpen}
				onClose={() => {
					setConfigOpen(false);
					setEditWidgetId(undefined);
				}}
				serviceId={instance.id}
				editWidgetId={editWidgetId}
			/>
		</div>
	);
}
