import "./FilterNameDialog.css";

import { Button, Dialog, Heading, Textfield } from "@digdir/designsystemet-react";
import { getLocalizedString } from "@olenbetong/appframe-core";
import { useEffect, useState } from "react";

export type FilterNameDialogProps = {
	open: boolean;
	/** Pre-fills the field, e.g. with the current filter's name. */
	defaultName?: string;
	/** Names already in use; entering one asks the user to confirm the overwrite. */
	existingNames?: string[];
	onCancel: () => void;
	onSubmit: (name: string) => void;
	"data-size"?: "sm" | "md" | "lg";
};

/**
 * Asks for the name to save a filter under.
 *
 * Reusing an existing name overwrites that filter, so the dialog warns before
 * submitting rather than silently creating a second filter with the same name.
 */
export function FilterNameDialog({
	open,
	defaultName = "",
	existingNames = [],
	onCancel,
	onSubmit,
	"data-size": size = "sm",
}: FilterNameDialogProps) {
	let [name, setName] = useState(defaultName);

	useEffect(() => {
		if (open) setName(defaultName);
	}, [open, defaultName]);

	let trimmed = name.trim();
	// A filter keeping its own name is an update, not a collision.
	let collides = trimmed !== defaultName && existingNames.some((existing) => existing === trimmed);

	function handleSubmit(event: React.FormEvent) {
		event.preventDefault();
		if (!trimmed) return;

		onSubmit(trimmed);
	}

	return (
		<Dialog open={open} closedby="any" data-size={size} className="ObFilterNameDialog-root" onClose={onCancel}>
			<form onSubmit={handleSubmit}>
				<Dialog.Block>
					<Heading level={2} data-size="xs">
						{getLocalizedString("Save filter")}
					</Heading>
				</Dialog.Block>
				<Dialog.Block>
					<Textfield
						// oxlint-disable-next-line jsx-a11y/no-autofocus -- the field is the only control in the dialog
						autoFocus
						data-size={size}
						label={getLocalizedString("Filter name")}
						value={name}
						error={
							collides ? getLocalizedString("A filter with this name already exists and will be replaced.") : undefined
						}
						onChange={(event) => setName(event.currentTarget.value)}
					/>
				</Dialog.Block>
				<Dialog.Block className="ObFilterNameDialog-actions">
					<Button type="submit" data-size={size} disabled={!trimmed}>
						{collides ? getLocalizedString("Replace") : getLocalizedString("Save")}
					</Button>
					<Button type="button" variant="secondary" data-size={size} onClick={onCancel}>
						{getLocalizedString("Cancel")}
					</Button>
				</Dialog.Block>
			</form>
		</Dialog>
	);
}
