import { registerFormatType, toggleFormat } from "@wordpress/rich-text";
import { __ } from "@wordpress/i18n";
import { BlockControls } from "@wordpress/block-editor";
import { Popover, Button } from "@wordpress/components";

import { ToolbarGroup, ToolbarButton, TextareaControl, ToggleControl, SelectControl } from "@wordpress/components";
import { check, trash } from "@wordpress/icons";

import { useState } from "@wordpress/element";

const TooltipFormatButton = (props) => {
	const { isActive, value, onChange } = props;
	const [isPopoverOpen, setIsPopoverOpen] = useState(false);
	const [popoverText, setPopoverText] = useState("");

	function handleFormat() {
		setIsPopoverOpen(!isPopoverOpen);
		onChange(
			toggleFormat(value, {
				type: "homegrade-format/tooltip",
				attributes: {
					"data-tooltip": popoverText,
					style: "text-decoration: underline;",
				},
			})
		);
	}
	function removeFormat() {
		setIsPopoverOpen(false);
		onChange(
			toggleFormat(value, {
				type: "homegrade-format/tooltip",
			})
		);
	}

	return (
		<>
			<BlockControls>
				{isPopoverOpen && (
					<Popover
						onClose={() => setIsPopoverOpen(false)}
						className='popover_tooltip_field'>
						<TextareaControl
							label='Text explicatif'
							help='Texte apparraissant au survol de la tooltip'
							onChange={(value) => setPopoverText(value)}
						/>
						<Button
							icon={check}
							variant='primary'
							onClick={() => {
								setIsPopoverOpen(false);
								handleFormat();
							}}>
							Valider
						</Button>
					</Popover>
				)}

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

registerFormatType("homegrade-format/tooltip", {
	title: __("Tooltip", "homegrade-format"),
	tagName: "span",
	className: "tooltip-word",
	edit: TooltipFormatButton,
});
