import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";

import { getDashboardSummary, type DashboardSummary } from "../api/dashboard";
import { checkInstanceHealth, type InstanceHealth } from "../api/sessions";
import { ErrorState, LoadingState } from "../components/data-states";
import { SessionList } from "../components/features/session/session-list";
import { useInstanceActions } from "../hooks/use-instance-actions";
import { useSessions } from "../state/sessions";

type HomeStatus = "loading" | "ready" | "error";

const summaryCards = [
	{ label: "Open sessions", key: "openSessions" },
	{ label: "Projects", key: "projects" },
	{ label: "Repositories", key: "repositories" },
] as const;

export const HomePage = () => {
	const navigate = useNavigate();
	const { sessions, refreshSessions } = useSessions();
	const [status, setStatus] = useState<HomeStatus>("loading");
	const [summary, setSummary] = useState<DashboardSummary | null>(null);
	const [tunnelHealth, setTunnelHealth] = useState<
		Record<string, InstanceHealth>
	>({});
	const safeSessions = Array.isArray(sessions) ? sessions : [];

	const loadHome = useCallback(async () => {
		setStatus("loading");
		try {
			const [dashboard] = await Promise.all([
				getDashboardSummary(),
				refreshSessions(),
			]);
			setSummary(dashboard);
			setStatus("ready");
		} catch {
			setStatus("error");
		}
	}, [refreshSessions]);

	useEffect(() => {
		void loadHome();
	}, [loadHome]);

	const {
		loadingSessionId: actionBusy,
		handleOpen,
		handleStart,
		handleStop,
		handleDelete,
		handleRecreateTunnel,
	} = useInstanceActions({ onRefresh: refreshSessions });

	// Poll tunnel health every 30 seconds for running instances
	useEffect(() => {
		const checkHealth = async () => {
			const runningSessions = safeSessions.filter(
				(s) => s.status === "running" && s.url,
			);
			for (const session of runningSessions) {
				try {
					const health = await checkInstanceHealth(
						session.project_id,
						session.repository_id,
						session.id,
					);
					setTunnelHealth((prev) => ({
						...prev,
						[session.id]: health,
					}));
				} catch {
					setTunnelHealth((prev) => ({
						...prev,
						[session.id]: {
							healthy: false,
							container_status: "unknown",
							container_health: null,
							container_exit_code: null,
							tunnel_status: "error",
							tunnel_status_code: null,
							probe_status: "error",
							last_probe_output: null,
							error: "check failed",
						},
					}));
				}
			}
		};

		void checkHealth();
		const interval = setInterval(() => {
			void checkHealth();
		}, 30000);
		return () => clearInterval(interval);
	}, [safeSessions]);

	const activeSessions = useMemo(
		() =>
			safeSessions.filter((session) =>
				["running", "building", "pending"].includes(session.status),
			),
		[safeSessions],
	);

	return (
		<section className="stack home-page">
			<header className="home-hero card">
				<div className="stack-sm">
					<p className="eyebrow">Workspace overview</p>
					<h1>Home</h1>
					<p className="muted">
						Open sessions, available projects, and the fastest path back into
						work.
					</p>
				</div>
				<div className="home-hero-actions">
					<button
						className="primary-button"
						type="button"
						onClick={() => navigate("/projects")}
					>
						New Project
					</button>
					<button
						className="secondary-button"
						type="button"
						onClick={() => navigate("/settings")}
					>
						Settings
					</button>
				</div>
			</header>

			{status === "loading" && <LoadingState message="Loading overview..." />}

			{status === "error" && (
				<ErrorState
					message="Unable to load your workspace overview."
					onRetry={() => void loadHome()}
				/>
			)}

			{status === "ready" && summary && (
				<>
					<div className="home-summary-grid">
						{summaryCards.map((card) => (
							<article className="card home-summary-card" key={card.label}>
								<p className="card-label">{card.label}</p>
								<p className="card-value">
									{card.key === "openSessions"
										? activeSessions.length
										: card.key === "projects"
											? summary.projects
											: summary.repositories}
								</p>
							</article>
						))}
					</div>

					<section className="card stack home-section">
						<div className="page-header">
							<div>
								<p className="eyebrow">Open sessions</p>
								<h2>
									{
										safeSessions.filter((s) =>
											[
												"running",
												"building",
												"pending",
												"starting",
												"probing",
												"unhealthy",
											].includes(s.status),
										).length
									}
								</h2>
							</div>
						</div>
						<SessionList
							sessions={safeSessions}
							onOpen={handleOpen}
							onStop={handleStop}
							onDelete={handleDelete}
							onRecreateTunnel={handleRecreateTunnel}
							actionBusyId={actionBusy}
							tunnelHealth={tunnelHealth}
							showGrouping={false}
							emptyMessage="No active sessions right now."
						/>
					</section>

					<section className="card stack home-section">
						<div className="page-header">
							<div>
								<p className="eyebrow">Workspaces</p>
								<h2>Quick access</h2>
							</div>
							<button
								className="secondary-button"
								type="button"
								onClick={() => navigate("/workspaces")}
							>
								View all
							</button>
						</div>
						<p className="muted">
							Use the floating button to start a tool in any workspace.
						</p>
					</section>

					{safeSessions.filter((s) => ["stopped", "error"].includes(s.status))
						.length > 0 && (
						<section className="card stack home-section">
							<div className="page-header">
								<div>
									<p className="eyebrow">Recent sessions</p>
									<h2>
										{
											safeSessions.filter((s) =>
												["stopped", "error"].includes(s.status),
											).length
										}
									</h2>
								</div>
							</div>
							<SessionList
								sessions={safeSessions}
								onOpen={handleOpen}
								onStart={handleStart}
								onDelete={handleDelete}
								actionBusyId={actionBusy}
								showGrouping={false}
								maxRecent={5}
								emptyMessage="No recent sessions."
							/>
						</section>
					)}
				</>
			)}
		</section>
	);
};

export { HomePage as DashboardPage };
