import { __ } from "@wordpress/i18n";
import { useBlockProps } from "@wordpress/block-editor";
import "./editor.scss";
import { useEntityRecord } from "@wordpress/core-data";
import { useState } from "@wordpress/element";
import { useSelect, useDispatch } from "@wordpress/data";
import { useEffect } from "@wordpress/element";
import { useEntityProp } from "@wordpress/core-data";
import chevronDown from "./img/chevron_down.svg";
import { getAdminLanguageFromCookie } from "../../utilities.js";

export default function Edit({ attributes, setAttributes }) {
	let { tooltipWords } = attributes;

	let [hasFetchedDatas, setHasFetchedDatas] = useState(false);

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

		const tooltipWords = [];

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

			tooltipWords.push({
				tooltipID,
				tooltipText,
				tooltipDefinition,
			});
		});
		return tooltipWords;
	}
	function parseBlocksTooltips(currentBlocks) {
		const blocksTooltipWords = [];
		currentBlocks.forEach((block) => {
			if (
				(block.name === "homegrade-content-blocks/questions-container" ||
					block.name === "homegrade-content-blocks/post-content-container") &&
				block?.attributes?.tooltipsWordsUsed?.length > 0
			) {
				block.attributes.tooltipsWordsUsed.forEach((tooltipWord) => {
					blocksTooltipWords.push(tooltipWord);
				});
			}
		});

		return blocksTooltipWords;
	}

	function filterToolTipsArray(tooltipWords) {
		const filteredTooltipWords = Array.from(
			new Map(
				tooltipWords.map((tooltipWord) => [tooltipWord.tooltipID, tooltipWord])
			).values()
		);

		return filteredTooltipWords;
		// const filteredTooltipWords = [];

		// tooltipWords.forEach((tooltipWord) => {
		// 	const existingTooltip = filteredTooltipWords.find(
		// 		(item) => item.tooltipID === tooltipWord.tooltipID,
		// 	);

		// 	if (!existingTooltip) {
		// 		filteredTooltipWords.push(tooltipWord);
		// 	}
		// });
	}
	function parseTooltipWords() {
		let newParsedTooltipWords = parseContentTooltips(currentPost.content);
		let newBlocksTooltipWords = parseBlocksTooltips(currentBlocks);

		let allTooltipWords = [...newParsedTooltipWords, ...newBlocksTooltipWords];
		const filteredTooltipWords = filterToolTipsArray(allTooltipWords);

		return filteredTooltipWords;
	}
	function buildTooltipWordsIdArray(tooltipsArray) {
		const tooltipWordsIds = tooltipsArray.map(
			(tooltipWord) => tooltipWord.tooltipID
		);
		return tooltipWordsIds;
	}

	function compareHasNewVocabularyWord(previousWords, newWords) {
		return !(JSON.stringify(previousWords) === JSON.stringify(newWords));
	}

	const currentPost = useSelect((select) =>
		select("core/editor").getCurrentPost()
	);

	const currentBlocks = useSelect((select) =>
		select("core/block-editor").getBlocks()
	);

	const currentTaxonomies = useSelect((select) =>
		select("core/editor").getCurrentPostAttribute("thematiques")
	);

	let currentThematique = useSelect(
		(select) =>
			select("core").getEntityRecord(
				"taxonomy",
				"thematiques",
				currentTaxonomies[0] // or currentPost.thematiques[0] works as well
			),
		[currentTaxonomies]
	);
	const tooltipWordsIds = buildTooltipWordsIdArray(tooltipWords);

	const vocabulairePosts = useSelect(
		(select) => {
			if (!tooltipWordsIds.length) return [];
			return select("core").getEntityRecords("postType", "vocabulaire", {
				per_page: -1,
				include: tooltipWordsIds,
			});
		},
		[tooltipWordsIds]
	);

	const currentLang = getAdminLanguageFromCookie("wp-wpml_current_language");
	const localBlockName = currentLang === "fr" ? "Vocabulaire" : "Woordenschat";
	useEffect(() => {
		if (currentPost.content && currentBlocks) {
			const newTooltipWords = parseTooltipWords();
			const newTooltipWordsDatas = buildTooltipWordsIdArray(newTooltipWords);

			if (compareHasNewVocabularyWord(tooltipWords, newTooltipWords)) {
				setAttributes({ tooltipWords: newTooltipWords });
			}
		}
	}, [currentPost, currentBlocks]);

	return (
		<section
			{...useBlockProps({
				className: `homegrade-blocks-vocabulaire-summary`,
			})}
		>
			<h2 className="homegrade-blocks-vocabulaire-summary__title">
				{localBlockName + " — "}
				{currentThematique && currentThematique.name
					? currentThematique.name
					: "...pas de thématique"}
			</h2>

			{vocabulairePosts &&
				vocabulairePosts.map((elem) => (
					<details className="question">
						<summary>
							{elem.title.rendered}
							<div className="open-close-icon">
								<img src={chevronDown} className="open-close-cta" alt="" />
							</div>
						</summary>
						<div className="homegrade-blocks-vocabulaire-summary__content-wrapper homegrade-dynamic-accordeon__content-wrapper">
							<div class=" homegrade-dynamic-accordeon__content">
								<p className="homegrade-blocks-vocabulaire-summary__content">
									{elem.acf.definition}
								</p>
							</div>
						</div>
					</details>
				))}
		</section>
	);
}
