import { __ } from "@wordpress/i18n";
import { registerFormatType, toggleFormat, applyFormat, getActiveFormats } from "@wordpress/rich-text";

import { BlockControls, __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import { Popover, ToolbarGroup, ToolbarButton } from "@wordpress/components";
import { trash } from "@wordpress/icons";
import { useState } from "@wordpress/element";
import { useSelect } from "@wordpress/data"; // pour les querry

const formatName = "homegrade-format/tooltip";

const Edit = (props) => {
	const { isActive, value, onChange } = props;
	const [isPopoverOpen, setIsPopoverOpen] = useState(false);
	const [pendingDefinition, setPendingDefinition] = useState(false);

	const activeFormat = getActiveFormats(value).filter((format) => format.type === formatName)[0];
	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 removeFormat() {
		setIsPopoverOpen(false);
		onChange(
			toggleFormat(value, {
				type: formatName,
			})
		);
	}
	function setFormat(postDatas) {
		setPendingDefinition(true);
		setIsPopoverOpen(false);

		onChange(
			applyFormat(value, {
				type: formatName,
				attributes: {
					definitionId: postDatas.id.toString(),
					dataTooltipWord: postDatas.title,
				},
			})
		);
	}

	const post = useSelect((select) => {
		if (activeFormat && activeFormat.attributes.definitionId) {
			return select("core").getEntityRecord(
				"postType",
				"vocabulaire",
				activeFormat.attributes.definitionId
			);
		}
	});

	if (post && pendingDefinition) {
		onChange(
			applyFormat(value, {
				type: formatName,
				attributes: {
					dataTooltipDefinition: post.acf.definition,
					definitionId: activeFormat.attributes.definitionId,
					dataTooltipWord: activeFormat.attributes.dataTooltipWord,
				},
			})
		);
		setPendingDefinition(false);
	}

	return (
		<>
			<BlockControls>
				{isPopoverOpen && (
					<Popover
						onClose={() => setIsPopoverOpen(false)}
						className='popover_tooltip_field'>
						<LinkControl
							value={
								post && activeFormat.attributes
									? {
											id: activeFormat.attributes
												.definitionId,
											url: post.link,
											tile: activeFormat.attributes
												.dataTooltipWord,
											type: "vocabulaire",
											kind: "post-type",
									  }
									: ""
							}
							suggestionsQuery={{
								type: "post",
								subtype: "vocabulaire",
								lang: lang,
							}}
							isCollapsed={true}
							onChange={(postDatas) => setFormat(postDatas)}
						/>
					</Popover>
				)}

				<ToolbarGroup>
					<ToolbarButton
						isActive={isActive}
						icon={!isActive ? "admin-comments" : "edit"}
						label={!isActive ? "Ajouter une tooltip" : "Éditer la tooltip"}
						onClick={() => {
							setIsPopoverOpen(true);
						}}
					/>
					{isActive && (
						<ToolbarButton
							icon={trash}
							label={"Supprimer la tooltip"}
							onClick={() => {
								removeFormat();
							}}
						/>
					)}
				</ToolbarGroup>
			</BlockControls>
		</>
	);
};

registerFormatType(formatName, {
	title: __("Tooltip", "homegrade-format"),
	tagName: "button",
	attributes: {
		definitionId: "data-definition-id",
		dataTooltipDefinition: "data-tooltip-definition",
		dataTooltipWord: "data-tooltip-word",
	},
	className: "tooltip-word",
	edit: Edit,
});
