import {useState} from "@wordpress/element";
import {Button, TextControl} from "@wordpress/components";

export default function CustomLinksSource({onAddItems}) {
	const [url, setUrl] = useState("https://");
	const [title, setTitle] = useState("");

	const add = () => {
		if (typeof onAddItems !== "function") return;

		const cleanUrl = String(url || "").trim();
		if (!cleanUrl) return;

		onAddItems([
			{
				type: "custom",
				url: cleanUrl,
				title: String(title || "").trim() || cleanUrl,
			},
		]);

		setTitle("");
	};

	return (
		<div className="jm-source">
			<TextControl
				label="URL"
				value={url}
				onChange={setUrl}
				__next40pxDefaultSize
				__nextHasNoMarginBottom
			/>
			<TextControl
				label="Link Text"
				value={title}
				onChange={setTitle}
				__next40pxDefaultSize
				__nextHasNoMarginBottom
			/>

			<Button variant="primary" onClick={add}>
				Add to menu
			</Button>
		</div>
	);
}
