import { ChipRemovable, Textfield } from "@digdir/designsystemet-react";
import { getLocalizedString } from "@olenbetong/appframe-core";
import { useState } from "react";

export type ChipListInputProps = {
	value: string[];
	onChange: (value: string[]) => void;
	readOnly?: boolean;
	"aria-label": string;
	"data-size"?: "sm" | "md" | "lg";
	type?: "text" | "number" | "date" | "datetime-local";
};

/**
 * Free text editor for the list operators. Values are added with Enter and
 * rendered as removable chips.
 */
export function ChipListInput({
	value,
	onChange,
	readOnly,
	type = "text",
	"aria-label": ariaLabel,
	"data-size": size,
}: ChipListInputProps) {
	let [draft, setDraft] = useState("");

	function commit() {
		let trimmed = draft.trim();
		if (!trimmed || value.includes(trimmed)) {
			setDraft("");
			return;
		}

		onChange([...value, trimmed]);
		setDraft("");
	}

	function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
		if (event.key === "Enter") {
			// The editor is often rendered inside a dialog; committing a value
			// must not submit or close it.
			event.preventDefault();
			commit();
		} else if (event.key === "Backspace" && draft === "" && value.length > 0) {
			onChange(value.slice(0, -1));
		}
	}

	return (
		<div className="ObFilterEditor-chipList">
			{value.map((item, index) => (
				<ChipRemovable
					// Values are deduplicated on add, so the value is a stable key.
					key={item}
					data-size={size}
					disabled={readOnly}
					aria-label={`${getLocalizedString("Remove")} ${item}`}
					onClick={() => onChange(value.filter((_, i) => i !== index))}
				>
					{item}
				</ChipRemovable>
			))}
			{!readOnly && (
				<Textfield
					className="ObFilterEditor-chipListInput"
					aria-label={ariaLabel}
					data-size={size}
					type={type}
					value={draft}
					placeholder={getLocalizedString("Add value")}
					onChange={(event) => setDraft(event.target.value)}
					onKeyDown={handleKeyDown}
					onBlur={commit}
				/>
			)}
		</div>
	);
}
