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

export default function PostTypeSource({restBase, typeSlug, onAddItems}) {
	const [loading, setLoading] = useState(true);
	const [items, setItems] = 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((p) => ({
					id: p.id,
					title: p?.title?.rendered || `(ID ${p.id})`,
				}));

				setItems(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: "post_type",
				object: typeSlug,
				object_id: Number(id),
				title: items.find((x) => String(x.id) === String(id))?.title || `Item ${id}`,
			}))
		);
	};

	if (loading) return <Spinner/>;

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

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