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

import { BlockControls, __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import { Popover, ToolbarGroup, ToolbarButton, TextControl, TextareaControl, Button } from "@wordpress/components";

import { trash, customPostType } from "@wordpress/icons";
import { useState } from "@wordpress/element";
import { useSelect } from "@wordpress/data";

import "./footnote.css";

const formatName = "carhop-format/footnote";

const FootnoteFormatButton = (props) => {
	const { isActive, value, onChange } = props;
	const [isPopoverOpen, setIsPopoverOpen] = useState(false);
	const hasSelection = value.start !== value.end;

	// Vérifier si on est dans un article (post type 'post')
	const postType = useSelect((select) => {
		return select("core/editor")?.getCurrentPostType();
	}, []);

	// Ne pas afficher le bouton si ce n'est pas un article
	if (postType !== "articles" || (!isActive && hasSelection)) {
		return null;
	}

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

	function handleFootnoteContentChange(value) {
		setFormat(value);
	}

	function removeFormat() {
		setIsPopoverOpen(false);
		const { text, formats, start, end } = value;
		const textLength = text ? text.length : 0;

		const isFootnoteAtIndex = (index) => {
			if (!formats || index < 0 || index >= (formats?.length || 0)) return false;
			const charFormats = formats[index];
			if (!charFormats) return false;
			return charFormats.some((f) => f && f.type === formatName);
		};

		if (textLength > 0) {
			let pos = Math.min(start, textLength - 1);
			// If caret is just after the formatted run, step back one char
			if (!isFootnoteAtIndex(pos) && pos > 0 && isFootnoteAtIndex(pos - 1)) {
				pos = pos - 1;
			}

			if (isFootnoteAtIndex(pos)) {
				let left = pos;
				let right = pos;
				while (left >= 0 && isFootnoteAtIndex(left)) left--;
				while (right < textLength && isFootnoteAtIndex(right)) right++;

				const spanStart = left + 1;
				const spanEnd = right; // exclusive

				// Supprimer toujours le texte complet de la footnote
				onChange(remove(value, spanStart, spanEnd));
				return;
			}
		}

		// Fallback: si aucune footnote n'est trouvée à la position du curseur,
		// enlever juste le formatage
		onChange(
			toggleFormat(value, {
				type: formatName,
			})
		);
	}
	function setFormat(footnoteContent) {
		onChange(
			applyFormat(value, {
				type: formatName,
				attributes: {
					dataFootnoteContent: footnoteContent,
				},
			})
		);
	}
	function insertFormat(footnoteContent) {
		const text = "[NOTE]";
		const start = value.start; // position du curseur avant insertion
		const nextValue = insert(value, text);

		onChange(
			applyFormat(
				nextValue,
				{
					type: formatName,
					attributes: { dataFootnoteContent: footnoteContent },
				},
				start,
				start + text.length
			)
		);
	}

	return (
		<>
			<BlockControls>
				{isPopoverOpen && (
					<Popover
						onClose={() => setIsPopoverOpen(false)}
						className='popover_footnote_field'>
						<TextareaControl
							__nextHasNoMarginBottom
							__next40pxDefaultSize
							label='Note de bas de page'
							value={activeFormat?.attributes?.dataFootnoteContent || ""}
							onChange={handleFootnoteContentChange}
						/>
						<div className='popover_footnote_field_buttons'>
							<Button
								variant='primary'
								onClick={() => setIsPopoverOpen(false)}>
								Ok
							</Button>
							<Button isDestructive onClick={() => removeFormat()}>
								Supprimer
							</Button>
						</div>
					</Popover>
				)}

				<ToolbarGroup>
					<ToolbarButton
						isActive={isActive}
						icon={customPostType}
						isPressed={isActive}
						label={
							!isActive
								? "Ajouter une note de bas de page"
								: "Éditer la note de bas de page"
						}
						onClick={() => {
							if (!isActive) {
								insertFormat();
							} else {
								setIsPopoverOpen(true);
							}
						}}
					/>
				</ToolbarGroup>
			</BlockControls>
		</>
	);
};

registerFormatType(formatName, {
	title: __("Notes de bas de page", "carhop-format-types"),
	tagName: "a",
	attributes: {
		dataFootnoteContent: "data-footnote-content",
	},
	className: "footnote-reference",
	edit: FootnoteFormatButton,
});
