import type { UpstreamHealth } from "@/lib/types";

function YesNo({ value, badValue }: { value: boolean; badValue: boolean }) {
	const bad = value === badValue;
	return <span className={bad ? "text-red-700 dark:text-red-400" : ""}>{value ? "yes" : "no"}</span>;
}

export default function UpstreamHealthTable({ health }: { health: UpstreamHealth }) {
	return (
		<section className="rounded border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-900">
			<h2 className="flex items-baseline justify-between px-4 pt-3 text-sm font-semibold">
				Upstreams
				<span className="text-xs font-normal text-zinc-500 tabular-nums">
					{health.available}/{health.total} available
				</span>
			</h2>
			{health.upstreams.length === 0 ? (
				<p className="px-4 py-3 text-sm text-zinc-500">No upstreams configured.</p>
			) : (
				<div className="overflow-x-auto">
					<table className="mt-2 w-full text-sm">
						<thead>
							<tr className="border-b border-zinc-200 text-left text-xs text-zinc-500 dark:border-zinc-800">
								<th scope="col" className="px-4 py-2 font-medium">
									URL
								</th>
								<th scope="col" className="px-4 py-2 font-medium">
									Enabled
								</th>
								<th scope="col" className="px-4 py-2 font-medium">
									Available
								</th>
								<th scope="col" className="px-4 py-2 text-right font-medium">
									Failures
								</th>
								<th scope="col" className="px-4 py-2 text-right font-medium">
									Success rate
								</th>
								<th scope="col" className="px-4 py-2 font-medium">
									Last error
								</th>
							</tr>
						</thead>
						<tbody>
							{health.upstreams.map((upstream) => (
								<tr
									key={upstream.url}
									className="border-b border-zinc-100 last:border-0 dark:border-zinc-800/50"
								>
									<td className="px-4 py-2 font-mono text-xs">{upstream.url}</td>
									<td className="px-4 py-2">
										<YesNo value={upstream.enabled} badValue={false} />
									</td>
									<td className="px-4 py-2">
										<YesNo value={upstream.available} badValue={false} />
									</td>
									<td className="px-4 py-2 text-right tabular-nums">{upstream.total_failures}</td>
									<td className="px-4 py-2 text-right tabular-nums">
										{(upstream.success_rate * 100).toFixed(1)}%
									</td>
									<td className="px-4 py-2 text-xs text-zinc-500">{upstream.last_error || "—"}</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
		</section>
	);
}
