import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { groupSourcesPutMutation, groupSourcesQuery } from "@/lib/queries";
import type { Blocklist } from "@/lib/types";
import { sameSet, toggleSource } from "./sourceSet";
import InlineError from "@/lib/InlineError";
import { buttonClass, focusRing, primaryButtonClass } from "@/ui/classes";

interface Props {
	groupId: number;
	blocklists: Blocklist[];
}

export default function GroupSourcesEditor({ groupId, blocklists }: Props) {
	const queryClient = useQueryClient();
	const sources = useQuery(groupSourcesQuery(groupId));
	const mutation = useMutation(groupSourcesPutMutation(queryClient));
	const [selected, setSelected] = useState<number[] | null>(null);

	if (sources.isPending) {
		return (
			<p role="status" className="mt-3 text-sm text-zinc-500">
				Loading sources…
			</p>
		);
	}
	if (sources.isError) return <InlineError error={sources.error} />;

	if (blocklists.length === 0) {
		return (
			<p className="mt-3 text-sm text-zinc-500">
				No blocklist sources exist yet — add them on the Blocklists page.
			</p>
		);
	}

	const current = selected ?? sources.data;
	const dirty = !sameSet(current, sources.data);

	return (
		<div className="mt-3">
			<ul className="space-y-1">
				{blocklists.map((blocklist) => (
					<li key={blocklist.id}>
						<label className="inline-flex items-center gap-2 text-sm">
							<input
								type="checkbox"
								checked={current.includes(blocklist.id)}
								onChange={() => setSelected(toggleSource(current, blocklist.id))}
								className={focusRing}
							/>
							{blocklist.name}
						</label>
					</li>
				))}
			</ul>
			<InlineError error={mutation.error} />
			<div className="mt-3 flex gap-2">
				<button
					type="button"
					disabled={!dirty || mutation.isPending}
					onClick={() =>
						mutation.mutate({ id: groupId, sourceIds: current }, { onSuccess: () => setSelected(null) })
					}
					className={primaryButtonClass}
				>
					Save sources
				</button>
				{dirty && (
					<button type="button" onClick={() => setSelected(null)} className={buttonClass}>
						Discard
					</button>
				)}
			</div>
		</div>
	);
}
