import { formatTime } from "@/lib/format";
import type { SourceStatus } from "@/lib/types";
import { tdClass, thClass } from "@/ui/classes";

function formatAttempt(unixSeconds: number): string {
	return unixSeconds === 0 ? "never" : formatTime(unixSeconds);
}

interface SourceStatusSectionProps {
	sources: SourceStatus[] | null;
	namesById: ReadonlyMap<number, string>;
}

export default function SourceStatusSection({ sources, namesById }: SourceStatusSectionProps) {
	return (
		<section className="mt-8">
			<h2 className="text-lg font-medium">Source status</h2>
			{sources === null ? (
				<p className="mt-2 text-zinc-500">
					No status snapshot yet — run “Update now” to fetch status for every enabled source.
				</p>
			) : sources.length === 0 ? (
				<p className="mt-2 text-zinc-500">The last update ran against no enabled sources.</p>
			) : (
				<div className="mt-2 overflow-x-auto">
					<table className="w-full min-w-max border-collapse text-sm">
						<thead>
							<tr>
								<th className={thClass}>Source</th>
								<th className={thClass}>State</th>
								<th className={thClass}>Last attempt</th>
								<th className={thClass}>Last success</th>
								<th className={thClass}>Domains</th>
								<th className={thClass}>Wildcards</th>
								<th className={thClass}>Skipped regex</th>
								<th className={thClass}>Last error</th>
							</tr>
						</thead>
						<tbody>
							{sources.map((source) => (
								<tr key={source.id}>
									<td className={tdClass}>
										<span className="font-medium">{namesById.get(source.id) ?? source.url}</span>
										<span className="mt-0.5 block max-w-64 truncate text-xs text-zinc-500">
											{source.url}
										</span>
									</td>
									<td className={tdClass}>
										<span
											className={
												source.loaded
													? "text-green-700 dark:text-green-400"
													: "text-red-600 dark:text-red-400"
											}
										>
											{source.state}
										</span>
									</td>
									<td className={tdClass}>{formatAttempt(source.last_attempt)}</td>
									<td className={tdClass}>{formatAttempt(source.last_success)}</td>
									<td className={`${tdClass} tabular-nums`}>{source.domains}</td>
									<td className={`${tdClass} tabular-nums`}>{source.wildcards}</td>
									<td className={`${tdClass} tabular-nums`}>{source.skipped_regex}</td>
									<td className={tdClass}>
										{source.last_error === "" ? (
											<span className="text-zinc-400">—</span>
										) : (
											<span className="text-red-600 dark:text-red-400">{source.last_error}</span>
										)}
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
		</section>
	);
}
