import { useReducer, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { clientPrefixesPutMutation } from "@/lib/queries";
import type { ClientPrefix, Group } from "@/lib/types";
import { defaultGroupId } from "@/lib/defaultGroup";
import { firstProblem, initPrefixEditor, isDirty, prefixEditorReducer, toInputs } from "./prefixEditor";
import InlineError from "@/lib/InlineError";
import { buttonClass, focusRing, primaryButtonClass, smallInputClass } from "@/ui/classes";

interface Props {
	prefixes: ClientPrefix[];
	groups: Group[];
}

export default function PrefixesEditor({ prefixes, groups }: Props) {
	const queryClient = useQueryClient();
	const mutation = useMutation(clientPrefixesPutMutation(queryClient));
	const [state, dispatch] = useReducer(prefixEditorReducer, prefixes, initPrefixEditor);
	const [validation, setValidation] = useState<string | null>(null);
	const dirty = isDirty(state);
	const fallbackGroupId = defaultGroupId(groups);

	const save = () => {
		const problem = firstProblem(state.rows);
		setValidation(problem);
		if (problem !== null) return;
		mutation.mutate(toInputs(state.rows), {
			onSuccess: (stored) => dispatch({ type: "reset", prefixes: stored }),
		});
	};

	return (
		<section className="mt-10">
			<h2 className="text-xl font-semibold">Client prefixes</h2>
			<p className="mt-1 text-sm text-zinc-500">
				Prefixes assign a group to whole address ranges. The list is saved as a whole; the highest priority
				match wins.
			</p>
			{state.rows.length === 0 ? (
				<p className="mt-4 text-sm text-zinc-500">No prefixes configured.</p>
			) : (
				<ul className="mt-4 space-y-2">
					{state.rows.map((row, index) => (
						<li key={index} className="flex flex-wrap items-center gap-2">
							<input
								type="text"
								aria-label={`Prefix ${index + 1}`}
								placeholder="192.168.1.0/24"
								value={row.prefix}
								onChange={(event) =>
									dispatch({ type: "edit", index, patch: { prefix: event.target.value } })
								}
								className={`${smallInputClass} w-52`}
							/>
							<select
								aria-label={`Group for prefix ${index + 1}`}
								value={String(row.group_id)}
								onChange={(event) =>
									dispatch({ type: "edit", index, patch: { group_id: Number(event.target.value) } })
								}
								className={smallInputClass}
							>
								{groups.map((group) => (
									<option key={group.id} value={String(group.id)}>
										{group.name}
									</option>
								))}
							</select>
							<input
								type="text"
								inputMode="numeric"
								aria-label={`Priority for prefix ${index + 1}`}
								placeholder="100"
								value={row.priority}
								onChange={(event) =>
									dispatch({ type: "edit", index, patch: { priority: event.target.value } })
								}
								className={`${smallInputClass} w-20`}
							/>
							<button
								type="button"
								onClick={() => dispatch({ type: "remove", index })}
								className={`rounded border border-zinc-300 px-2 py-1.5 text-sm text-red-700 ${focusRing} dark:border-zinc-700 dark:text-red-400`}
							>
								Remove
							</button>
						</li>
					))}
				</ul>
			)}
			{validation !== null && (
				<p role="alert" className="mt-2 text-sm text-red-700 dark:text-red-400">
					{validation}
				</p>
			)}
			<InlineError error={mutation.error} />
			<div className="mt-4 flex gap-2">
				<button
					type="button"
					onClick={() => dispatch({ type: "add", groupId: fallbackGroupId })}
					className={buttonClass}
				>
					Add prefix
				</button>
				<button
					type="button"
					onClick={save}
					disabled={!dirty || mutation.isPending}
					className={primaryButtonClass}
				>
					Save prefixes
				</button>
				{dirty && (
					<button
						type="button"
						onClick={() => {
							setValidation(null);
							dispatch({ type: "reset", prefixes });
						}}
						className={buttonClass}
					>
						Discard changes
					</button>
				)}
			</div>
		</section>
	);
}
