import {useEffect, useMemo, useState} from "@wordpress/element";
import {__experimentalHeading as Heading, Notice, Panel, PanelBody, Spinner} from "@wordpress/components";
import {getTypes, getTaxonomies} from "./api";
import PostTypeSource from "./sources/PostTypeSource";
import TaxonomySource from "./sources/TaxonomySource";
import CustomLinksSource from "./sources/CustomLinksSource";
import {HIDDEN_POST_TYPES} from "./constants/heddenPostTypes";

export default function AddItemsPanel({menuId, onAddItems}) {
	const [types, setTypes] = useState(null);
	const [tax, setTax] = useState(null);
	const [loading, setLoading] = useState(true);

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

		Promise.all([getTypes(), getTaxonomies()])
			.then(([t, x]) => {
				if (!alive) return;
				setTypes(t);
				setTax(x);
			})
			.finally(() => alive && setLoading(false));

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


	const postTypePanels = useMemo(() => {
		if (!types) return [];

		return Object.keys(types)
			.sort((a, b) => {
				const an = types[a]?.name || a;
				const bn = types[b]?.name || b;
				return String(an).localeCompare(String(bn));
			})
			.map((slug) => ({slug, data: types[slug]}))
			.filter(({data, slug}) => {
				if (!data?.rest_base) return false;
				if (HIDDEN_POST_TYPES.includes(slug)) return false;
				if (data?.slug === "wp_block") return false;
				return true;
			});
	}, [types]);

	const taxonomyPanels = useMemo(() => {
		if (!tax) return [];
		return Object.keys(tax)
			.sort()
			.map((k) => ({slug: k, data: tax[k]}))
			.filter(({data}) => data?.rest_base);
	}, [tax]);

	return (
		<>
			<Heading className="jet-menu-card__title" level={3}>Add menu items</Heading>
			<div style={{marginTop: "12px"}}>
				{!menuId ? (
				<Notice status="warning" isDismissible={false}>
					Select or create a menu first.
				</Notice>
			) : loading ? (
				<Spinner/>
			) : !types || !tax ? (
				<Notice status="warning" isDismissible={false}>
					Failed to load sources.
				</Notice>
			) : (
				<Panel header="">
					<PanelBody title="Custom Links" initialOpen>
						<CustomLinksSource onAddItems={onAddItems}/>
					</PanelBody>

					<PanelBody title="Pages / Posts / CPT" initialOpen={false}>
						{postTypePanels.map(({slug, data}) => (
							<PanelBody key={slug} title={data?.name || slug} initialOpen={slug === "page"}>
								<PostTypeSource
									label={data?.name || slug}
									restBase={data.rest_base}
									typeSlug={data.slug || slug}
									onAddItems={onAddItems}
								/>
							</PanelBody>
						))}
					</PanelBody>

					<PanelBody title="Taxonomies" initialOpen={false}>
						{taxonomyPanels.map(({slug, data}) => (
							<PanelBody key={slug} title={data?.name || slug} initialOpen={false}>
								<TaxonomySource
									label={data?.name || slug}
									restBase={data.rest_base}
									taxonomySlug={data.slug || slug}
									onAddItems={onAddItems}
								/>
							</PanelBody>
						))}
					</PanelBody>
				</Panel>
			)}
			</div>
		</>
	);
}
