import "./editor.scss";
import "./focus-point-thematique";

import { __ } from "@wordpress/i18n";
import { useSelect, dispatch } from "@wordpress/data";
import { useEffect } from "@wordpress/element";
import { createBlock } from "@wordpress/blocks";
import { store as coreStore } from "@wordpress/core-data";

import { useBlockProps, InspectorControls } from "@wordpress/block-editor";
import { withNotices, Button, PanelBody } from "@wordpress/components";
import { InnerBlocks } from "@wordpress/block-editor";

import chevronDown from "./img/chevron_down.svg";
import getAdminLanguageFromCookies from "../../../utils/getAdminLanguageFromCookies.js";

function Edit({
	attributes,
	setAttributes,
	noticeOperations,
	noticeList,
	noticeUI,
	clientId,
	...props
}) {
	const { coverUrl, coverId, coverAlt, focusBullets } = attributes;
	const currentBlockDatas = useSelect((select) => {
		return select("core/block-editor").getBlocksByClientId(clientId)[0];
	});

	let children = useSelect(
		(select) =>
			select("core/block-editor").getBlocksByClientId(clientId)[0].innerBlocks
	);

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

	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;

	let thematiqueCover = useSelect(
		(select) => {
			if (
				currentGeneralThematique &&
				currentGeneralThematique.acf.taxonomy_pictures &&
				currentGeneralThematique.acf.taxonomy_pictures.illustration_xl
			) {
				let thematiqueMediaId =
					currentGeneralThematique.acf.taxonomy_pictures.illustration_xl;
				const media = select(coreStore).getMedia(thematiqueMediaId, {
					context: "view",
				});
				return media;
			}
			return null;
		},
		[currentGeneralThematique]
	);

	function updateCoverImg(thematiqueCoverDatas) {
		if (thematiqueCoverDatas && thematiqueCoverDatas.source_url !== coverUrl) {
			setAttributes({
				coverUrl: thematiqueCoverDatas.source_url,
				coverAlt: thematiqueCoverDatas.alt_text,
			});
		}
	}

	function passCoverUrlToChildren() {
		if (children && coverUrl) {
			children.forEach(function (child) {
				dispatch("core/block-editor").updateBlockAttributes(child.clientId, {
					coverUrl: coverUrl,
				});
			});
		}
	}

	function passIndexToChildren() {
		if (children) {
			children.forEach((child, index) => {
				dispatch("core/block-editor").updateBlockAttributes(child.clientId, {
					focusIndex: index + 1,
				});
			});
		}
	}

	function updateFocusPointBullets() {
		if (children) {
			const focusBullets = children.map((child, index) => {
				return {
					title: child.attributes.focusTitle,
					x: child.attributes.focusPosition.x,
					y: child.attributes.focusPosition.y,
				};
			});

			setAttributes({ focusBullets });
		}
	}

	function insertFocusPointBlock() {
		const index = children && children.length ? children.length : 0;
		const newBlock = createBlock(
			"homegrade-content-blocks/focus-point-thematique",
			{}
		);
		dispatch("core/block-editor").insertBlocks(newBlock, index, clientId);
	}

	function handleBulletClick(index) {
		if (currentBlockDatas && currentBlockDatas.innerBlocks) {
			dispatch("core/block-editor").selectBlock(
				currentBlockDatas.innerBlocks[index].clientId
			);
		}
	}

	const renderedFocusPointBullets = focusBullets.map((focusBullet, index) => {
		return (
			<div
				data-focus-bullet-title={focusBullet.title}
				className="homegrade-blocks-focus-point-bullet"
				style={{
					top: `${focusBullet.y * 100}%`,
					left: `${focusBullet.x * 100}%`,
				}}
				onClick={() => handleBulletClick(index)}
			>
				<span className="homegrade-blocks-focus-point-bullet__index">
					{index + 1}
				</span>{" "}
			</div>
		);
	});

	useEffect(() => {
		if (thematiqueCover && thematiqueCover.source_url) {
			updateCoverImg(thematiqueCover);
		}
	}, [thematiqueCover]);

	useEffect(() => {
		updateFocusPointBullets();
	}, []);

	useEffect(() => {
		updateFocusPointBullets();
		passCoverUrlToChildren();
	}, [children]);
	useEffect(() => {
		passIndexToChildren();
	}, [currentBlockDatas]);

	const currentLang = getAdminLanguageFromCookies("wp-wpml_current_language");
	const localVersionTextDescription =
		currentLang === "nl"
			? "Tekstversie van de instructies in de afbeelding"
			: "Version texte des indications de l'illustration";

	return (
		<>
			<InspectorControls>
				<PanelBody>
					<Button
						variant="primary"
						onClick={() => {
							insertFocusPointBlock();
						}}
					>
						Ajouter un point Légende
					</Button>
				</PanelBody>
			</InspectorControls>

			<section
				{...useBlockProps({
					className: `homegrade-blocks-focused-thematique`,
				})}
			>
				{coverUrl && (
					<figure className="picture-container">
						<img src={coverUrl} alt={coverAlt} />
						{renderedFocusPointBullets}
					</figure>
				)}

				<button
					className="homegrade-blocks-focused-thematique__figcaption-toggle"
					aria-expanded="false"
				>
					{localVersionTextDescription}
					{/* <ChevronDown /> */}
					<img src={chevronDown} alt="" />
				</button>
				<figcaption aria-hidden="true">
					<ol>
						<InnerBlocks
							allowedBlocks={[
								"homegrade-content-blocks/focus-point-thematique",
							]}
						/>
					</ol>
				</figcaption>
			</section>
		</>
	);
}

export default withNotices(Edit);
