import { QueryCells, QueryTableHead } from "@/features/queries/QueryLogPage";
import { RING_CAPACITY } from "./ringBuffer";
import { useLiveQueries, type EventSourceFactory, type StreamStatus } from "./useLiveQueries";
import { buttonClass, retryButtonClass, tableWrapClass } from "@/ui/classes";

const toolbarButtonClass = `${buttonClass} font-medium`;

function StatusPill({ status }: { status: StreamStatus }) {
	const styles: Record<StreamStatus, [string, string]> = {
		connecting: ["Connecting…", "bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300"],
		open: ["Live", "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"],
		retrying: ["Reconnecting…", "bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"],
		capped: ["Disconnected", "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"],
	};
	const [label, tone] = styles[status];
	return (
		<span role="status" aria-label={label} className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${tone}`}>
			{label}
		</span>
	);
}

/** Freeze is display-only: the stream stays open and the 500-row ring buffer keeps
 * filling; Resume shows the current buffer (anything pushed out meanwhile is gone). */
export default function LiveLogPage({ createEventSource }: { createEventSource?: EventSourceFactory } = {}) {
	const live = useLiveQueries({ createEventSource });

	return (
		<section>
			<div className="flex flex-wrap items-center gap-3">
				<h1 className="text-2xl font-semibold">Live</h1>
				<StatusPill status={live.status} />
				<button
					type="button"
					onClick={live.toggleFreeze}
					aria-pressed={live.frozen}
					className={toolbarButtonClass}
				>
					{live.frozen ? "Resume" : "Freeze"}
				</button>
			</div>

			{live.frozen && (
				<p className="mt-2 text-sm text-zinc-500" role="status">
					Display frozen — new queries keep buffering ({live.liveCount} in buffer, newest {RING_CAPACITY}{" "}
					kept).
				</p>
			)}

			{live.missed !== null && (
				<div
					role="status"
					className="mt-3 flex items-center gap-3 rounded border border-blue-300 bg-blue-50 px-3 py-2 text-sm text-blue-800 dark:border-blue-900 dark:bg-blue-950 dark:text-blue-200"
				>
					<span>
						Stream resumed —{" "}
						{live.missed === 0 ? "no queries missed" : `${live.missed} missed queries recovered`}.
					</span>
					<button type="button" onClick={live.dismissMissed} className="font-medium underline">
						Dismiss
					</button>
				</div>
			)}

			{live.resyncFailed && (
				<p role="alert" className="mt-3 text-sm text-red-700 dark:text-red-300">
					Stream resumed, but re-syncing the gap failed — some queries may be missing here.
				</p>
			)}

			{live.status === "capped" && (
				<div
					role="alert"
					className="mt-4 rounded border border-red-300 bg-red-50 p-4 dark:border-red-900 dark:bg-red-950"
				>
					<h2 className="font-semibold text-red-800 dark:text-red-200">Live stream unavailable</h2>
					<p className="mt-1 text-sm text-red-700 dark:text-red-300">
						The connection failed repeatedly — possibly too many live viewers (the server caps streams per
						address), or the server is unreachable.
					</p>
					<button type="button" onClick={live.retry} className={retryButtonClass}>
						Retry
					</button>
				</div>
			)}

			{live.rows.length === 0 ? (
				live.status !== "capped" && (
					<p className="mt-6 text-zinc-500">
						{live.status === "open" ? "Waiting for queries…" : "No queries received yet."}
					</p>
				)
			) : (
				<>
					<div className={`${tableWrapClass} rounded border border-zinc-200 dark:border-zinc-800`}>
						<table className="w-full text-sm">
							<QueryTableHead />
							<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
								{live.rows.map((row) => (
									<tr key={row.key} className={row.blocked ? "bg-red-50 dark:bg-red-950/40" : ""}>
										<QueryCells row={row} />
									</tr>
								))}
							</tbody>
						</table>
					</div>
					<p className="mt-3 text-sm text-zinc-500">
						Showing {live.rows.length} {live.rows.length === 1 ? "query" : "queries"} (newest first, last{" "}
						{RING_CAPACITY} kept).
					</p>
				</>
			)}
		</section>
	);
}
