import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { formatTime } from "@/lib/format";
import InlineError from "@/lib/InlineError";
import {
	blocklistCreateMutation,
	blocklistDeleteMutation,
	blocklistUpdateMutation,
	blocklistsQuery,
	blocklistsUpdateNowMutation,
} from "@/lib/queries";
import type { Blocklist, BlocklistInput } from "@/lib/types";
import BlocklistForm from "./BlocklistForm";
import { useRefreshStatus } from "./refreshStore";
import SourceStatusSection from "./SourceStatusSection";
import {
	dangerLinkButtonClass,
	focusRing,
	linkButtonClass,
	primaryButtonClass,
	tableWrapClass,
	tdClass,
	thClass,
} from "@/ui/classes";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";

export default function BlocklistsPage() {
	const queryClient = useQueryClient();
	const { data: blocklists } = useSuspenseQuery(blocklistsQuery());
	const [editing, setEditing] = useState<Blocklist | null>(null);

	const create = useMutation(blocklistCreateMutation(queryClient));
	const save = useMutation(blocklistUpdateMutation(queryClient));
	const toggle = useMutation(blocklistUpdateMutation(queryClient));
	const remove = useMutation(blocklistDeleteMutation(queryClient));
	const updateNow = useMutation(blocklistsUpdateNowMutation(queryClient));

	const sources = useRefreshStatus();
	const namesById = new Map(blocklists.map((b) => [b.id, b.name]));
	// The refresh below re-fetches the sources the config already declares, so
	// it stays live in file mode; every other control here writes config.
	const readOnly = useReadOnlyConfig();

	async function submitForm(input: BlocklistInput) {
		if (editing === null) {
			await create.mutateAsync(input);
		} else {
			await save.mutateAsync({ id: editing.id, input: { ...input, is_suggested: editing.is_suggested } });
			setEditing(null);
		}
	}

	function toggleEnabled(b: Blocklist) {
		toggle.mutate({
			id: b.id,
			input: { url: b.url, name: b.name, enabled: !b.enabled, is_suggested: b.is_suggested },
		});
	}

	function deleteBlocklist(b: Blocklist) {
		if (window.confirm(`Delete blocklist "${b.name}"? Its domains stop being blocked.`)) {
			remove.mutate(b.id);
		}
	}

	const formError = editing === null ? create.error : save.error;
	const tableError = remove.error ?? toggle.error;

	return (
		<section>
			<div className="flex flex-wrap items-center justify-between gap-3">
				<h1 className="text-2xl font-semibold">Blocklists</h1>
				<button
					type="button"
					onClick={() => updateNow.mutate()}
					disabled={updateNow.isPending}
					className={primaryButtonClass}
				>
					{updateNow.isPending ? "Updating…" : "Update now"}
				</button>
			</div>
			{updateNow.isSuccess && !updateNow.isPending && (
				<p className="mt-2 text-sm text-green-700 dark:text-green-400" role="status">
					Update completed; source status refreshed below.
				</p>
			)}
			<InlineError error={updateNow.error} />

			{blocklists.length === 0 ? (
				<p className="mt-4 text-zinc-500">No blocklist sources yet. Add one below.</p>
			) : (
				<div className={tableWrapClass}>
					<table className="w-full min-w-max border-collapse text-sm">
						<thead>
							<tr>
								<th className={thClass}>Name</th>
								<th className={thClass}>URL</th>
								<th className={thClass}>Enabled</th>
								<th className={thClass}>Domains</th>
								<th className={thClass}>Wildcards</th>
								<th className={thClass}>Skipped regex</th>
								<th className={thClass}>Last updated</th>
								<th className={thClass}>
									<span className="sr-only">Actions</span>
								</th>
							</tr>
						</thead>
						<tbody>
							{blocklists.map((b) => (
								<tr key={b.id}>
									<td className={tdClass}>
										<span className="font-medium">{b.name}</span>
										{b.is_suggested && (
											<span className="ml-2 rounded bg-zinc-200 px-1.5 py-0.5 text-xs text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300">
												Suggested
											</span>
										)}
									</td>
									<td className={tdClass}>
										<span className="block max-w-72 truncate" title={b.url}>
											{b.url}
										</span>
									</td>
									<td className={tdClass}>
										<input
											type="checkbox"
											aria-label={`${b.name} enabled`}
											checked={b.enabled}
											disabled={toggle.isPending || readOnly}
											title={readOnly ? READ_ONLY_HINT : undefined}
											onChange={() => toggleEnabled(b)}
											className={focusRing}
										/>
									</td>
									<td className={`${tdClass} tabular-nums`}>{b.domain_count}</td>
									<td className={`${tdClass} tabular-nums`}>{b.wildcard_count}</td>
									<td className={`${tdClass} tabular-nums`}>{b.skipped_regex_count}</td>
									<td className={tdClass}>
										{b.last_updated === null ? "never" : formatTime(b.last_updated)}
									</td>
									<td className={tdClass}>
										<div className="flex gap-3">
											<button
												type="button"
												onClick={() => setEditing(b)}
												disabled={readOnly}
												title={readOnly ? READ_ONLY_HINT : undefined}
												className={`${linkButtonClass} disabled:opacity-50`}
											>
												Edit
											</button>
											<button
												type="button"
												onClick={() => deleteBlocklist(b)}
												disabled={remove.isPending || readOnly}
												title={readOnly ? READ_ONLY_HINT : undefined}
												className={dangerLinkButtonClass}
											>
												Delete
											</button>
										</div>
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
			<InlineError error={tableError} />

			<BlocklistForm
				key={editing?.id ?? "add"}
				initial={editing ?? undefined}
				busy={editing === null ? create.isPending : save.isPending}
				readOnly={readOnly}
				error={formError}
				onSubmit={submitForm}
				onCancel={editing === null ? undefined : () => setEditing(null)}
			/>

			<SourceStatusSection sources={sources} namesById={namesById} />
		</section>
	);
}
