import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { clientUpdateMutation } from "@/lib/queries";
import type { Client, Group } from "@/lib/types";
import InlineError from "@/lib/InlineError";
import { buttonClass, primaryButtonClass, smallInputClass } from "@/ui/classes";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";

interface Props {
	client: Client;
	groups: Group[];
	onClose: () => void;
}

const dialogInputClass = `mt-1 w-full ${smallInputClass}`;

export default function ClientEditDialog({ client, groups, onClose }: Props) {
	const queryClient = useQueryClient();
	const mutation = useMutation(clientUpdateMutation(queryClient));
	const [name, setName] = useState(client.name);
	const [groupId, setGroupId] = useState(client.group_id);
	const readOnly = useReadOnlyConfig();

	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
			<div
				role="dialog"
				aria-modal="true"
				aria-label={`Edit client ${client.ip}`}
				className="w-full max-w-md rounded-lg border border-zinc-200 bg-white p-6 shadow-lg dark:border-zinc-700 dark:bg-zinc-900"
			>
				<h2 className="text-lg font-semibold">Edit {client.ip}</h2>
				<form
					className="mt-4 space-y-4"
					onSubmit={(event) => {
						event.preventDefault();
						mutation.mutate(
							{ id: client.id, edit: { name: name.trim(), group_id: groupId } },
							{ onSuccess: onClose },
						);
					}}
				>
					<label className="block text-sm font-medium">
						Name
						<input
							type="text"
							value={name}
							onChange={(event) => setName(event.target.value)}
							className={dialogInputClass}
							autoFocus
						/>
					</label>
					<label className="block text-sm font-medium">
						Group
						<select
							value={String(groupId)}
							onChange={(event) => setGroupId(Number(event.target.value))}
							className={dialogInputClass}
						>
							{groups.map((group) => (
								<option key={group.id} value={String(group.id)}>
									{group.name}
								</option>
							))}
						</select>
					</label>
					<InlineError error={mutation.error} />
					<div className="flex justify-end gap-2">
						<button type="button" onClick={onClose} className={buttonClass}>
							Cancel
						</button>
						<button
							type="submit"
							disabled={mutation.isPending || readOnly}
							title={readOnly ? READ_ONLY_HINT : undefined}
							className={primaryButtonClass}
						>
							Save
						</button>
					</div>
				</form>
			</div>
		</div>
	);
}
