import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { clientUpdateMutation } from "@/lib/queries";
import type { Client, Group } from "@/lib/types";
import InlineError from "@/lib/InlineError";
import Dialog from "@/ui/Dialog";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";

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

const styles = stylex.create({
	heading: {
		fontSize: "1.125rem",
		lineHeight: "1.75rem",
		fontWeight: 600,
	},
	form: {
		display: "flex",
		flexDirection: "column",
		gap: "1rem",
		marginTop: "1rem",
	},
	fieldLabel: {
		display: "block",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		fontWeight: 500,
	},
	dialogInput: {
		marginTop: "0.25rem",
		width: "100%",
	},
	actions: {
		display: "flex",
		justifyContent: "flex-end",
		gap: "0.5rem",
	},
});

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 (
		<Dialog label={`Edit client ${client.ip}`} isOpen onClose={onClose}>
			<h2 {...stylex.props(styles.heading)}>Edit {client.ip}</h2>
			<form
				{...stylex.props(styles.form)}
				onSubmit={(event) => {
					event.preventDefault();
					mutation.mutate(
						{ id: client.id, edit: { name: name.trim(), group_id: groupId } },
						{ onSuccess: onClose },
					);
				}}
			>
				<label {...stylex.props(styles.fieldLabel)}>
					Name
					<input
						type="text"
						value={name}
						onChange={(event) => setName(event.target.value)}
						autoFocus
						{...stylex.props(shared.smallInput, styles.dialogInput, shared.focusRing)}
					/>
				</label>
				<Select
					label="Group"
					variant="compactField"
					value={String(groupId)}
					onChange={(value) => setGroupId(Number(value))}
					options={groups.map((group) => ({ value: String(group.id), label: group.name }))}
				/>
				<InlineError error={mutation.error} />
				<div {...stylex.props(styles.actions)}>
					<button type="button" onClick={onClose} {...stylex.props(shared.button, shared.focusRing)}>
						Cancel
					</button>
					<button
						type="submit"
						disabled={mutation.isPending || readOnly}
						title={readOnly ? READ_ONLY_HINT : undefined}
						{...stylex.props(shared.primaryButton, shared.focusRing)}
					>
						Save
					</button>
				</div>
			</form>
		</Dialog>
	);
}
