import { __ } from "@wordpress/i18n";
import { useEffect, useState } from "@wordpress/element";
import {
	useBlockProps,
	MediaPlaceholder,
	BlockControls,
	InspectorControls,
	MediaReplaceFlow,
} from "@wordpress/block-editor";
import {
	ToolbarGroup,
	ToolbarButton,
	Spinner,
	withNotices,
	FocalPointPicker,
	PanelBody,
	ToggleControl,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from "@wordpress/components";
import "./editor.scss";
import { isBlobURL, revokeBlobURL } from "@wordpress/blob";

function Edit({
	attributes,
	setAttributes,
	noticeOperations,
	noticeList,
	noticeUI,
	...props
}) {
	const {
		coverUrl,
		coverId,
		coverAlt,
		coverCaption,
		coverDescription,
		heightFixed,
		imagePosition,
	} = attributes;
	const [blobUrl, setBlobUrl] = useState();

	function onUploadError(message) {
		noticeOperations.removeAllNotices();
		noticeOperations.createErrorNotice(message);
	}
	function removeCoverImg() {
		setAttributes({
			coverUrl: undefined,
			coverId: undefined,
			coverAlt: "",
			coverCaption: "",
			coverDescription: "",
		});
	}

	function updateCoverImage(image) {
		if (!image || !image.url) {
			return removeCoverImg();
		}
		setAttributes({
			coverUrl: image.url,
			coverId: image.id,
			coverAlt: image.alt,
			coverCaption: image.caption,
			coverDescription: image.description,
		});
	}

	function onHeightFixedChange(heightFixed) {
		setAttributes({ heightFixed });
	}

	// Si l'upload s'est mal passé -> reset
	useEffect(() => {
		if (!coverId && isBlobURL(coverUrl)) {
			setAttributes({ coverUrl: undefined, coverAlt: "" });
		}
	}, []);

	useEffect(() => {
		// Fonction de clean du BLOB URL qui se lance à chaque changement de coverUrl
		if (isBlobURL(coverUrl)) {
			// Si la cover est une blob, c'est que ça upload donc on met cette url dans le state
			setBlobUrl(coverUrl);
		} else {
			// Si la cover en'est plus une blob, c'est que l'upload est terminé, on revoke la blob et on clean le state
			revokeBlobURL(blobUrl); // On utilise la valeur stocké dans le state pour revoke l'url
			setBlobUrl();
		}
	}, [coverUrl]);
	return (
		<>
			<InspectorControls>
				{coverUrl && (
					<PanelBody title="Image de couverture">
						<ToggleGroupControl
							label="Hauteur"
							className="homegrade-blocks-highlight__variant"
							isBlock
							onChange={onHeightFixedChange}
							value={heightFixed}
						>
							<ToggleGroupControlOption label="Fixe" value={true} />
							<ToggleGroupControlOption label="Entière" value={false} />
						</ToggleGroupControl>
						<FocalPointPicker
							label="position"
							url={coverUrl}
							dimensions={{
								width: 400,
								height: 100,
							}}
							value={imagePosition}
							onChange={(focalPoint) => {
								setAttributes({ imagePosition: focalPoint });
							}}
						/>
					</PanelBody>
				)}
			</InspectorControls>
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						icon={"fullscreen-exit-alt"}
						label="Hauteur Fixe"
						isActive={heightFixed}
						onClick={() => onHeightFixedChange(true)}
					/>
					<ToolbarButton
						icon={"editor-expand"}
						label="Hauteur Pleine"
						isActive={!heightFixed}
						onClick={() => onHeightFixedChange(false)}
					/>
				</ToolbarGroup>
				{coverUrl && (
					<>
						<MediaReplaceFlow
							group="inline"
							name="Remplacer l'image"
							disableMediaButtons={coverUrl}
							icon="trash"
							onSelect={updateCoverImage}
							onError={onUploadError}
							accept="image/*" // On upload Allow only images
							allowedTypes={["image"]} // Onlibrary Allow only images
							notices={noticeUI} // En cas d'erreur d'upload
							mediaId={coverId}
							mediaURL={coverUrl}
						/>
						<ToolbarButton
							icon={"trash"}
							title="Supprimer l'image"
							onClick={removeCoverImg}
						/>
					</>
				)}
			</BlockControls>

			<figure
				{...useBlockProps({
					className: `homegrade-content-blocks-picture-banner ${
						isBlobURL(coverUrl) ? "is-loading" : ""
					} ${heightFixed ? "fixed-height" : ""} `,
				})}
			>
				{coverUrl && (
					<>
						<img
							src={coverUrl}
							alt={coverAlt}
							style={{
								objectPosition: `${imagePosition.x * 100}% ${
									imagePosition.y * 100
								}%`,
							}}
						/>
						{coverCaption && (
							<figcaption className="homegrade-content-blocks-picture-banner__caption">
								{coverCaption}
							</figcaption>
						)}
						{isBlobURL(coverUrl) && <Spinner />}
					</>
				)}

				<MediaPlaceholder
					disableMediaButtons={coverUrl}
					icon="admin-appearance"
					onSelect={updateCoverImage}
					onError={onUploadError}
					accept="image/*" // On upload Allow only images
					allowedTypes={["image"]} // Onlibrary Allow only images
					notices={noticeUI} // En cas d'erreur d'upload
				/>
			</figure>
		</>
	);
}

export default withNotices(Edit);
