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

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

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

const formatName = "homegrade-format/brochure-format";

const BrochureLinkFormatButton = (props) => {
	const { isActive, value, onChange } = props;
	const [isPopoverOpen, setIsPopoverOpen] = useState(false);
	const [linkValue, setLinkValue] = useState("");

	const activeFormat = getActiveFormats(value).filter((format) => format.type === formatName)[0];

	function setFormat() {
		setIsPopoverOpen(!isPopoverOpen);
		onChange(
			applyFormat(value, {
				type: formatName,
				attributes: {
					href: linkValue.url,
					target: "_blank",
					dataId: linkValue.id.toString(),
					style: "text-decoration: underline;",
				},
			})
		);
	}
	function removeFormat() {
		setIsPopoverOpen(false);
		setLinkValue("");
		onChange(
			toggleFormat(value, {
				type: formatName,
			})
		);
	}

	return (
		<>
			<BlockControls>
				{isPopoverOpen && (
					<Popover
						onClose={() => setIsPopoverOpen(false)}
						className='popover_tooltip_field'>
						<LinkControl
							suggestionsQuery={{
								type: "attachment",
								// subtype: "application/pdf", // Not working
								// mime_type: "application/pdf", // Not working
							}}
							value={linkValue}
							onChange={(value) => {
								setLinkValue(value);
							}}
						/>
						<Button
							icon={check}
							variant='primary'
							onClick={() => {
								setIsPopoverOpen(!isPopoverOpen);
								setFormat();
							}}>
							Valider
						</Button>
					</Popover>
				)}

				<ToolbarGroup className='test'>
					<ToolbarButton
						isActive={isActive}
						icon={!isActive ? "book" : trash}
						label={
							!isActive
								? "Ajouter un lien brochure"
								: "Supprimer le lien brochure"
						}
						onClick={() =>
							!isActive ? setIsPopoverOpen(!isPopoverOpen) : removeFormat()
						}
					/>
				</ToolbarGroup>
			</BlockControls>
		</>
	);
};

registerFormatType("homegrade-format/brochure-format", {
	title: "Lien Brochure",
	tagName: "a",
	className: "brochure-link-format",
	edit: BrochureLinkFormatButton,
});
