import { __ } from "@wordpress/i18n";
import { InspectorControls } from "@wordpress/block-editor";
import {
	PanelBody,
	SelectControl,
	ComboboxControl,
} from "@wordpress/components";
import "./editor.scss";
import { useSelect } from "@wordpress/data";
import { useEffect, useState } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";

export default function OptionsSelectControl({
	setAttributes,
	chapterLinkRelatedPostId,
}) {
	let [relatedQuestionPages, setRelatedQuestionPages] = useState(null);
	let [childTermsIdArray, setChildTermsIdArray] = useState(null);

	const lang = getAdminLanguageFromCookie("wp-wpml_current_language");

	function getAdminLanguageFromCookie(c_name) {
		var c_value = document.cookie,
			c_start = c_value.indexOf(" " + c_name + "=");
		if (c_start == -1) c_start = c_value.indexOf(c_name + "=");
		if (c_start == -1) {
			c_value = null;
		} else {
			c_start = c_value.indexOf("=", c_start) + 1;
			var c_end = c_value.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = c_value.length;
			}
			c_value = unescape(c_value.substring(c_start, c_end));
		}
		return c_value;
	}

	function handleRelatedPostChange(postId) {
		setAttributes({ chapterLinkRelatedPostId: Number(postId) });
	}

	function buildTaxChildrenIdArray(childrenArray) {
		return childrenArray.map((item) => item.id);
	}

	function buildSelectOptions(relatedPossiblePages) {
		let options = [];
		if (relatedPossiblePages) {
			options.push({ value: 0, label: "Sélectionnez une page" });
			relatedPossiblePages.forEach((page) => {
				options.push({
					value: page.id,
					label: decodeEntities(page.title.rendered),
				});
			});
		} else {
			options.push({ value: 0, label: "Pas encore de questions..." });
		}
		return options;
	}

	// GET TAXONOMIES INOFRMATION
	let postTaxonomies = useSelect((select) =>
		select("core/editor").getCurrentPostAttribute("thematiques")
	);

	// GET THE CURRENT TAXONOMY AND FIND THE PARENT OBJECT
	let postMainTaxonomy = useSelect(
		(select) =>
			select("core").getEntityRecord(
				"taxonomy",
				"thematiques",
				postTaxonomies[0]
			),
		[postTaxonomies]
	);
	let postParentTaxonomy = useSelect(
		(select) => {
			if (postMainTaxonomy && postMainTaxonomy.parent) {
				return select("core").getEntityRecord(
					"taxonomy",
					"thematiques",
					postMainTaxonomy.parent
				);
			}
			return null;
		},
		[postMainTaxonomy]
	);
	let currentGeneralThematique = postParentTaxonomy ?? postMainTaxonomy ?? null;

	// GET THE PARENT TAX CHILDREN
	let childTerms = useSelect((select) => {
		if (currentGeneralThematique) {
			return select("core").getEntityRecords("taxonomy", "thematiques", {
				parent: currentGeneralThematique.id,
			});
		}
		return null;
	});

	// BUILD AN ARRAY OF CHILDREN TAXONOMIES ID AND PUT IT IN THE STATE
	useEffect(() => {
		if (childTerms) {
			setChildTermsIdArray(buildTaxChildrenIdArray(childTerms));
		}
	}, [childTerms]);

	// GET OPTIONS FOR RELATED POSSIBLE PAGES ACCORDING TO CURRENT TAXONOMY CHILDREN ID ARRAY
	const relatedPossiblePages = useSelect((select) => {
		if (childTermsIdArray) {
			let query = {
				status: "publish",
				per_page: -1,
				lang: lang,
				thematiques: childTermsIdArray,
			};
			return select("core").getEntityRecords("postType", "conseils", query);
		}
		return null;
	});

	useEffect(() => {
		if (relatedPossiblePages) {
			setRelatedQuestionPages(buildSelectOptions(relatedPossiblePages));
		}
	}, [relatedPossiblePages]);

	let panelTitle = postParentTaxonomy
		? "Conseils " + postParentTaxonomy.name
		: postMainTaxonomy
		? "Conseils " + postMainTaxonomy.name
		: null;

	return (
		<InspectorControls>
			<PanelBody title={__("Conseils Relié", "homegrade-blocks")}>
				{/* <SelectControl
					label={panelTitle}
					value={chapterLinkRelatedPostId}
					options={relatedQuestionPages}
					onChange={(e) => handleRelatedPostChange(e)}
				/> */}
				{relatedQuestionPages && (
					<ComboboxControl
						label={panelTitle}
						onChange={(e) => handleRelatedPostChange(e)}
						options={relatedQuestionPages}
						value={chapterLinkRelatedPostId}
					/>
				)}
			</PanelBody>
		</InspectorControls>
	);
}
