import { __ } from "@wordpress/i18n";
import { useBlockProps } from "@wordpress/block-editor";
import { Notice } from "@wordpress/components";
import { store as noticesStore } from "@wordpress/notices";
import { useDispatch } from "@wordpress/data";

import { useSelect } from "@wordpress/data"; // pour les querry
import "./editor.scss";
import { RawHTML } from "@wordpress/element";
import { useEffect } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";
import OptionsSelectControl from "./OptionsSelectControl";
import { Button } from "@wordpress/components";

function parseBlockContentForTooltips(editorContent) {
	const parser = new DOMParser();
	const doc = parser.parseFromString(editorContent, "text/html");
	const domTooltipWords = doc.querySelectorAll(".tooltip-word");

	const filteredTooltipWords = [];

	// Looping over tooltip words and filtering duplicates
	Array.from(domTooltipWords).forEach((tooltipWord) => {
		const tooltipID = tooltipWord.getAttribute("data-definition-id");
		const tooltipText = tooltipWord.getAttribute("data-tooltip-word");
		const tooltipDefinition = tooltipWord.getAttribute(
			"data-tooltip-definition"
		);

		const existingTooltip = filteredTooltipWords.find(
			(item) => item.tooltipID === tooltipID
		);

		if (!existingTooltip) {
			filteredTooltipWords.push({
				tooltipID,
				tooltipText,
				tooltipDefinition,
			});
		}
	});
	return filteredTooltipWords;
}

export default function Edit({ attributes, setAttributes }) {
	const { relatedPostId } = attributes;
	const { createErrorNotice } = useDispatch(noticesStore);

	let currentRelatedPost = useSelect((select) =>
		select("core").getEntityRecord("postType", "questions", relatedPostId)
	);

	useEffect(() => {
		if (currentRelatedPost) {
			const currentBlockTooltips = parseBlockContentForTooltips(
				currentRelatedPost.content.rendered
			);
			setAttributes({ tooltipsWordsUsed: currentBlockTooltips });
		}

		if (!relatedPostId) {
			createErrorNotice(
				__("Un bloc question est vide ou n'est relié à aucune question"),
				{
					explicitDismiss: true,
				}
			);
		}
	}, [currentRelatedPost]);

	return (
		<>
			<OptionsSelectControl
				relatedPostId={relatedPostId}
				setAttributes={setAttributes}
			/>

			<section
				{...useBlockProps({
					className: `questions-container`,
				})}
			>
				{!relatedPostId && (
					<>
						<Notice status="error" isDismissible={false}>
							<p>
								{__(
									"Ce bloc n'est relié à aucune question. Rattachez-le à une fiche question dans la barre latérale.",
									"homegrade-blocks__texte-backoffice"
								)}
							</p>
						</Notice>
					</>
				)}

				{currentRelatedPost && (
					<>
						<h3>{decodeEntities(currentRelatedPost.title.rendered)}</h3>
						<RawHTML>{currentRelatedPost.content.rendered}</RawHTML>
					</>
				)}
			</section>
		</>
	);
}
