import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
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 ConfirmDialog from "@/ui/ConfirmDialog";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import Switch from "@/ui/Switch";
import AuthorityGate from "./AuthorityGate";
import BlocklistForm from "./BlocklistForm";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import { styles as config } from "./styles";

const SKIPPED_NOTE =
	"Both “Skipped” columns count lines nxdns read and did not take. Skipped regex lines are patterns nxdns accepts " +
	"only from you — adopt one you trust as a regex rule. Skipped unsupported lines are syntax nxdns cannot translate " +
	"into a DNS decision: cosmetic element hiding, browser-only modifiers. A skipped unsupported count that dwarfs the " +
	"domain count usually means the list is written for a browser extension, and its DNS or hosts variant will block " +
	"more here.";

const styles = stylex.create({
	name: {
		fontWeight: 500,
	},
	badge: {
		marginLeft: "0.5rem",
		borderRadius: "0.25rem",
		backgroundColor: colors.border,
		paddingInline: "0.375rem",
		paddingBlock: "0.125rem",
		fontSize: "0.75rem",
		lineHeight: "1rem",
		color: colors.text,
	},
	url: {
		display: "block",
		maxWidth: "18rem",
		overflow: "hidden",
		textOverflow: "ellipsis",
		whiteSpace: "nowrap",
	},
	actions: {
		display: "flex",
		gap: "0.75rem",
	},
	dimWhenDisabled: {
		opacity: { default: 1, ":disabled": 0.5 },
	},
});

/**
 * A runtime action: it re-downloads the sources the running process already
 * knows about, so it stays enabled under file authority and while
 * `/api/config/status` is still answering.
 *
 * The feedback is the action's own, and it is transient: started while the
 * request is in flight, the failure verbatim if it fails, and nothing on
 * success — the refreshed counters are the success signal, and a standing
 * "counters refreshed" line would claim a refetch that may itself have failed.
 * Durable per-source outcomes live in Diagnostics.
 */
function UpdateNowAction() {
	const queryClient = useQueryClient();
	const updateNow = useMutation(blocklistsUpdateNowMutation(queryClient));
	return (
		<div {...stylex.props(config.actionRow)}>
			<button
				type="button"
				onClick={() => updateNow.mutate()}
				disabled={updateNow.isPending}
				{...stylex.props(shared.primaryButton, shared.focusRing)}
			>
				{updateNow.isPending ? "Updating…" : "Update now"}
			</button>
			{updateNow.isPending && (
				<p role="status" {...stylex.props(config.note)}>
					Update started…
				</p>
			)}
			<InlineError error={updateNow.error} />
		</div>
	);
}

export default function ProtectionSources() {
	const blocklists = useQuery(blocklistsQuery());
	return (
		<div>
			<p {...stylex.props(config.intro)}>
				The shared catalogue every group draws from. A group subscribes to sources on the Groups tab.
			</p>
			<UpdateNowAction />
			<AuthorityGate>
				{(status) =>
					status.authority === "managed_file" ? (
						<>
							<FileModeNote path={status.path} />
							<QueryPanel query={blocklists}>
								{(rows) => <SourcesReadOnly blocklists={rows} />}
							</QueryPanel>
						</>
					) : (
						<QueryPanel query={blocklists}>{(rows) => <SourcesEditor blocklists={rows} />}</QueryPanel>
					)
				}
			</AuthorityGate>
		</div>
	);
}

/**
 * File mode is a different rendering of the same facts, not a smaller set of
 * them: the Suggested provenance and both skipped-line counters belong here
 * too. A list whose lines nxdns could not take is a failure the reader must
 * see under either authority.
 */
function SourcesReadOnly({ blocklists }: { blocklists: Blocklist[] }) {
	return (
		<section {...stylex.props(config.panel)}>
			<h2 {...stylex.props(config.panelHeading)}>
				Blocklist sources
				<code {...stylex.props(shared.mono, config.panelKey)}>blocklist_sources</code>
			</h2>
			{blocklists.length === 0 ? (
				<p {...stylex.props(config.empty)}>The file declares no blocklist sources.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(config.table)}>
						<thead>
							<tr>
								<th {...stylex.props(shared.th)}>Name</th>
								<th {...stylex.props(shared.th)}>URL</th>
								<th {...stylex.props(shared.th)}>Enabled</th>
								<th {...stylex.props(shared.th)}>Domains</th>
								<th {...stylex.props(shared.th)}>Wildcards</th>
								<th {...stylex.props(shared.th)}>Exceptions</th>
								<th {...stylex.props(shared.th)}>Skipped regex</th>
								<th {...stylex.props(shared.th)}>Skipped unsupported</th>
								<th {...stylex.props(shared.th)}>Last updated</th>
							</tr>
						</thead>
						<tbody>
							{blocklists.map((b) => (
								<tr key={b.id}>
									<td {...stylex.props(shared.td)}>
										<span {...stylex.props(styles.name)}>{b.name}</span>
										{b.is_suggested && <span {...stylex.props(styles.badge)}>Suggested</span>}
									</td>
									<td {...stylex.props(shared.td, shared.mono)}>{b.url}</td>
									<td {...stylex.props(shared.td)}>{String(b.enabled)}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.domain_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.wildcard_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.exception_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.skipped_regex_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>
										{b.skipped_unsupported_count}
									</td>
									<td {...stylex.props(shared.td)}>
										{b.last_updated === null ? "never" : formatTime(b.last_updated)}
									</td>
								</tr>
							))}
						</tbody>
					</table>
					<p {...stylex.props(config.note)}>{SKIPPED_NOTE}</p>
				</div>
			)}
		</section>
	);
}

function SourcesEditor({ blocklists }: { blocklists: Blocklist[] }) {
	const queryClient = useQueryClient();
	const [editing, setEditing] = useState<Blocklist | null>(null);
	const [pendingDelete, setPendingDelete] = useState<Blocklist | null>(null);

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

	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 confirmDelete() {
		if (pendingDelete === null) return;
		remove.mutate(pendingDelete.id);
		setPendingDelete(null);
	}

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

	return (
		<div>
			{blocklists.length === 0 ? (
				<p {...stylex.props(config.empty)}>No blocklist sources yet. Add one below.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(config.table)}>
						<thead>
							<tr>
								<th {...stylex.props(shared.th)}>Name</th>
								<th {...stylex.props(shared.th)}>URL</th>
								<th {...stylex.props(shared.th)}>Enabled</th>
								<th {...stylex.props(shared.th)}>Domains</th>
								<th {...stylex.props(shared.th)}>Wildcards</th>
								<th {...stylex.props(shared.th)}>Exceptions</th>
								<th {...stylex.props(shared.th)}>Skipped regex</th>
								<th {...stylex.props(shared.th)}>Skipped unsupported</th>
								<th {...stylex.props(shared.th)}>Last updated</th>
								<th {...stylex.props(shared.th)}>
									<span {...stylex.props(shared.srOnly)}>Actions</span>
								</th>
							</tr>
						</thead>
						<tbody>
							{blocklists.map((b) => (
								<tr key={b.id}>
									<td {...stylex.props(shared.td)}>
										<span {...stylex.props(styles.name)}>{b.name}</span>
										{b.is_suggested && <span {...stylex.props(styles.badge)}>Suggested</span>}
									</td>
									<td {...stylex.props(shared.td)}>
										<span {...stylex.props(styles.url)} title={b.url}>
											{b.url}
										</span>
									</td>
									<td {...stylex.props(shared.td)}>
										<Switch
											aria-label={`${b.name} enabled`}
											isSelected={b.enabled}
											isDisabled={toggle.isPending}
											onChange={() => toggleEnabled(b)}
										/>
									</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.domain_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.wildcard_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.exception_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{b.skipped_regex_count}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>
										{b.skipped_unsupported_count}
									</td>
									<td {...stylex.props(shared.td)}>
										{b.last_updated === null ? "never" : formatTime(b.last_updated)}
									</td>
									<td {...stylex.props(shared.td)}>
										<div {...stylex.props(styles.actions)}>
											<button
												type="button"
												onClick={() => setEditing(b)}
												{...stylex.props(shared.linkButton, shared.focusRing)}
											>
												Edit
											</button>
											<button
												type="button"
												onClick={() => setPendingDelete(b)}
												disabled={remove.isPending}
												{...stylex.props(
													shared.dangerLinkButton,
													styles.dimWhenDisabled,
													shared.focusRing,
												)}
											>
												Delete
											</button>
										</div>
									</td>
								</tr>
							))}
						</tbody>
					</table>
					<p {...stylex.props(config.note)}>{SKIPPED_NOTE}</p>
				</div>
			)}
			<InlineError error={tableError} />

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

			<ConfirmDialog
				isOpen={pendingDelete !== null}
				title="Delete blocklist"
				message={
					pendingDelete === null
						? ""
						: `Delete blocklist "${pendingDelete.name}"? Its domains stop being blocked.`
				}
				confirmLabel="Delete"
				onConfirm={confirmDelete}
				onCancel={() => setPendingDelete(null)}
			/>
		</div>
	);
}
