import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } 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 BlocklistForm from "./BlocklistForm";
import { useRefreshStatus } from "./refreshStore";
import SourceStatusSection from "./SourceStatusSection";
import ConfirmDialog from "@/ui/ConfirmDialog";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";

const styles = stylex.create({
	header: {
		display: "flex",
		flexWrap: "wrap",
		alignItems: "center",
		justifyContent: "space-between",
		gap: "0.75rem",
	},
	heading: {
		fontSize: "1.5rem",
		lineHeight: "2rem",
		fontWeight: 600,
	},
	done: {
		marginTop: "0.5rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.primaryOnSurface,
	},
	empty: {
		marginTop: "1rem",
		color: colors.textMuted,
	},
	table: {
		width: "100%",
		minWidth: "max-content",
		borderCollapse: "collapse",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
	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 },
	},
});

export default function BlocklistsPage() {
	const queryClient = useQueryClient();
	const { data: blocklists } = useSuspenseQuery(blocklistsQuery());
	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));
	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 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 (
		<section>
			<div {...stylex.props(styles.header)}>
				<h1 {...stylex.props(styles.heading)}>Blocklists</h1>
				<button
					type="button"
					onClick={() => updateNow.mutate()}
					disabled={updateNow.isPending}
					{...stylex.props(shared.primaryButton, shared.focusRing)}
				>
					{updateNow.isPending ? "Updating…" : "Update now"}
				</button>
			</div>
			{updateNow.isSuccess && !updateNow.isPending && (
				<p {...stylex.props(styles.done)} role="status">
					Update completed; source status refreshed below.
				</p>
			)}
			<InlineError error={updateNow.error} />

			{blocklists.length === 0 ? (
				<p {...stylex.props(styles.empty)}>No blocklist sources yet. Add one below.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(styles.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)}>Skipped regex</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)}>
										<input
											type="checkbox"
											aria-label={`${b.name} enabled`}
											checked={b.enabled}
											disabled={toggle.isPending || readOnly}
											title={readOnly ? READ_ONLY_HINT : undefined}
											onChange={() => toggleEnabled(b)}
											{...stylex.props(shared.focusRing)}
										/>
									</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.skipped_regex_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)}
												disabled={readOnly}
												title={readOnly ? READ_ONLY_HINT : undefined}
												{...stylex.props(
													shared.linkButton,
													styles.dimWhenDisabled,
													shared.focusRing,
												)}
											>
												Edit
											</button>
											<button
												type="button"
												onClick={() => setPendingDelete(b)}
												disabled={remove.isPending || readOnly}
												title={readOnly ? READ_ONLY_HINT : undefined}
												{...stylex.props(shared.dangerLinkButton, shared.focusRing)}
											>
												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} />

			<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)}
			/>
		</section>
	);
}
