import { useCallback, useEffect, useState } from "react";

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

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

export const SessionsPage = () => {
	const { sessions, isLoading, error, refreshSessions } = useSessions();
	const [status, setStatus] = useState<SessionsStatus>("loading");
	const [lastSessionId, setLastSessionId] = useState<string | null>(null);

	const [tunnelHealth, setTunnelHealth] = useState<
		Record<string, InstanceHealth>
	>({});

	const loadPageData = useCallback(async () => {
		setStatus("loading");
		try {
			await refreshSessions();
			const config = await getUserConfig();
			setLastSessionId(config.last_session_id ?? null);
			setStatus("ready");
		} catch {
			setStatus("error");
		}
	}, [refreshSessions]);

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

	const {
		loadingSessionId,
		dirtyDeleteSession,
		dirtyDeleteFiles,
		handleOpen,
		handleStart,
		handleStop,
		handleDelete,
		handleForceDelete,
		handleRecreateTunnel,
		handleRename,
		clearDirtyDelete,
	} = useInstanceActions({ onRefresh: refreshSessions });

	// Poll health every 30 seconds for active web-enabled instances
	useEffect(() => {
		const checkHealth = async () => {
			const activeSessions = sessions.filter(
				(s) =>
					["running", "starting", "unhealthy", "probing"].includes(s.status) &&
					s.tool_type_interfaces?.includes("web"),
			);
			for (const session of activeSessions) {
				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,
							tunnel_status: "unreachable",
							tunnel_status_code: null,
							probe_status: "unknown",
							last_probe_output: null,
							error: "check failed",
						} as InstanceHealth,
					}));
				}
			}
		};

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

	const lastSession = sessions.find((s) => s.id === lastSessionId) ?? null;

	const isPageLoading = status === "loading" || (status === "ready" && isLoading && sessions.length === 0);

	return (
		<section className="stack sessions-page">
			<div className="page-header">
				<h1>Sessions</h1>
			</div>

			{status === "error" && (
				<ErrorState
					message={error?.message ?? "Failed to load sessions"}
					onRetry={() => void loadPageData()}
				/>
			)}

			{(status === "loading" || isPageLoading) && (
				<LoadingState message="Loading sessions..." />
			)}

			{status === "ready" && !isPageLoading && (
				<>
					{/* Last Session */}
					{lastSession && (
						<div className="last-session-section">
							<h2>Last Session</h2>
							<SessionCard
								session={lastSession}
								onOpen={handleOpen}
								onDelete={handleDelete}
								onRename={handleRename}
								isBusy={loadingSessionId === lastSession.id}
								tunnelHealth={tunnelHealth[lastSession.id] || null}
							/>
						</div>
					)}

					{/* Session List */}
					<div className="sessions-list-wrapper">
						<SessionList
							sessions={sessions}
							onOpen={handleOpen}
							onStart={handleStart}
							onStop={handleStop}
							onDelete={handleDelete}
							onRecreateTunnel={handleRecreateTunnel}
							onRename={handleRename}
							actionBusyId={loadingSessionId}
							tunnelHealth={tunnelHealth}
						/>
					</div>

					{/* Create Session — use floating button */}
					<div className="create-session-section">
						<h2>Start New Tool</h2>
						<p className="muted">
							Use the floating button (bottom-right) to start a tool in any
							workspace.
						</p>
					</div>

					{/* Dirty Delete Confirmation Modal */}
					{dirtyDeleteSession && (
						<div className="modal-overlay" onClick={clearDirtyDelete}>
							<div
								className="modal-content"
								onClick={(e) => e.stopPropagation()}
							>
								<h3>Uncommitted Changes</h3>
								<p>
									The repository{" "}
									<strong>{dirtyDeleteSession.repository_name}</strong> has
									uncommitted changes. Deleting this session will permanently
									lose these changes.
								</p>
								<div className="changed-files-list">
									<h4>Changed files:</h4>
									<ul>
										{dirtyDeleteFiles.map((file, idx) => (
											<li key={idx}>{file}</li>
										))}
									</ul>
								</div>
								<div className="modal-actions">
									<button
										className="secondary-button"
										onClick={clearDirtyDelete}
										type="button"
									>
										Cancel
									</button>
									<button
										className="danger-button"
										onClick={() => void handleForceDelete(dirtyDeleteSession)}
										type="button"
									>
										Force Delete
									</button>
								</div>
							</div>
						</div>
					)}
				</>
			)}
		</section>
	);
};
