import {useEffect, useState} from "@wordpress/element";
import {Button, CheckboxControl, Spinner} from "@wordpress/components";
import apiFetch from "@wordpress/api-fetch";

export default function TaxonomySource({restBase, taxonomySlug, onAddItems}) {
	const [loading, setLoading] = useState(true);
	const [terms, setTerms] = useState([]);
	const [selected, setSelected] = useState({});

	useEffect(() => {
		let alive = true;

		(async () => {
			setLoading(true);
			try {
				const res = await apiFetch({path: `/wp/v2/${restBase}?per_page=100&context=edit`});
				if (!alive) return;

				const list = (res || []).map((t) => ({
					id: t.id,
					name: t.name || `(ID ${t.id})`,
				}));

				setTerms(list);
				setSelected({});
			} finally {
				if (alive) setLoading(false);
			}
		})();

		return () => {
			alive = false;
		};
	}, [restBase]);

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

		const picked = Object.keys(selected).filter((id) => selected[id]);
		if (!picked.length) return;

		onAddItems(
			picked.map((id) => ({
				type: "taxonomy",
				object: taxonomySlug,
				object_id: Number(id),
				title: terms.find((x) => String(x.id) === String(id))?.name || `Term ${id}`,
			}))
		);
	};

	if (loading) return <Spinner/>;

	return (
		<div className="jm-source">
			{terms.map((t) => (
				<CheckboxControl
					key={t.id}
					label={t.name}
					checked={!!selected[t.id]}
					onChange={(v) => setSelected((p) => ({...p, [t.id]: v}))}
				/>
			))}

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