import { useState, type FormEvent } from "react";
import { ApiError } from "@/lib/api";
import InlineError from "@/lib/InlineError";
import type { Blocklist, BlocklistInput } from "@/lib/types";
import { buttonClass, focusRing, inputClass, primaryButtonClass } from "@/ui/classes";

/**
 * Drops the rejection the page already renders inline below the form. Anything
 * else is a bug in this component and must reach the console instead of dying
 * silently in the submit handler.
 */
export function swallowMutationError(error: unknown): void {
	if (error instanceof ApiError) return;
	throw error;
}

interface BlocklistFormProps {
	initial?: Blocklist;
	busy: boolean;
	error: Error | null;
	onSubmit: (input: BlocklistInput) => Promise<void>;
	onCancel?: () => void;
}

export default function BlocklistForm({ initial, busy, error, onSubmit, onCancel }: BlocklistFormProps) {
	const [url, setUrl] = useState(initial?.url ?? "");
	const [name, setName] = useState(initial?.name ?? "");
	const [enabled, setEnabled] = useState(initial?.enabled ?? true);

	async function handleSubmit(event: FormEvent<HTMLFormElement>) {
		event.preventDefault();
		try {
			await onSubmit({ url: url.trim(), name: name.trim(), enabled });
		} catch (error) {
			swallowMutationError(error);
			return;
		}
		if (initial === undefined) {
			setUrl("");
			setName("");
			setEnabled(true);
		}
	}

	return (
		<form onSubmit={handleSubmit} className="mt-4 max-w-xl space-y-3">
			<h2 className="text-lg font-medium">{initial === undefined ? "Add source" : `Edit ${initial.name}`}</h2>
			<div>
				<label htmlFor="blocklist-url" className="block text-sm font-medium">
					URL
				</label>
				<input
					id="blocklist-url"
					type="url"
					required
					value={url}
					onChange={(event) => setUrl(event.target.value)}
					className={inputClass}
				/>
			</div>
			<div>
				<label htmlFor="blocklist-name" className="block text-sm font-medium">
					Name
				</label>
				<input
					id="blocklist-name"
					type="text"
					required
					value={name}
					onChange={(event) => setName(event.target.value)}
					className={inputClass}
				/>
			</div>
			<label className="flex items-center gap-2 text-sm font-medium">
				<input
					type="checkbox"
					checked={enabled}
					onChange={(event) => setEnabled(event.target.checked)}
					className={focusRing}
				/>
				Enabled
			</label>
			<div className="flex items-center gap-2">
				<button type="submit" disabled={busy} className={primaryButtonClass}>
					{initial === undefined ? "Add source" : "Save changes"}
				</button>
				{onCancel !== undefined && (
					<button type="button" onClick={onCancel} className={`${buttonClass} font-medium`}>
						Cancel
					</button>
				)}
			</div>
			<InlineError error={error} />
		</form>
	);
}
