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

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 });
			if (initial === undefined) {
				setUrl("");
				setName("");
				setEnabled(true);
			}
		} catch {
			// The page renders the mutation error inline below the form.
		}
	}

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