import { __ } from "@wordpress/i18n";
import { useBlockProps } from "@wordpress/block-editor";

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";

export default function Edit({ attributes, setAttributes }) {
	const { relatedPostId, postType, relatedPostPreviewGhostContent } =
		attributes;
	let currentRelatedPost = useSelect(
		(select) =>
			relatedPostId && postType
				? select("core").getEntityRecord("postType", postType, relatedPostId)
				: null,
		[relatedPostId, postType]
	);

	// console.log("relatedPostPreviewGhostContent", relatedPostPreviewGhostContent);

	// useEffect(() => {
	// 	if (currentRelatedPost?.content?.rendered) {
	// 		setAttributes({
	// 			relatedPostPreviewGhostContent: currentRelatedPost.content.rendered,
	// 		});
	// 	} else {
	// 		setAttributes({
	// 			relatedPostPreviewGhostContent: null,
	// 		});
	// 	}
	// }, [currentRelatedPost]);

	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;
	}

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

	// 	const editedContent = wp.data.select("core/editor").getEditedPostContent();
	// 	function getContent() {
	//     // Récupérer et retourner le contenu personnalisé ici
	//     return 'Votre contenu personnalisé';
	// }
	// useEffect(() => {
	// 	if (!rankMathEditor) return;

	// 	wp.hooks.addFilter("rank_math_content", "rank-math", updateContent);
	// 	function updateContent() {
	// 		return editedContent;
	// 	}
	// 	rankMathEditor.refresh("content");
	// }, [rankMathEditor]);

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

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

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