import { __ } from "@wordpress/i18n";
import "./editor.scss";
import {
	useBlockProps,
	MediaPlaceholder,
	BlockControls,
	InspectorControls,
	MediaReplaceFlow,
} from "@wordpress/block-editor";

import {
	Button,
	PanelBody,
	Tip,
	ToggleControl,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from "@wordpress/components";
import { trash } from "@wordpress/icons";

export default function Edit({
	attributes,
	setAttributes,
	noticeOperations,
	noticeList,
	noticeUI,
}) {
	const {
		hasStickyLegend,
		hasLightbox,
		legendLocation,
		hasFixedHeight,
		hasRoundedShadow,
		showTitle,
		pictureUrl,
		pictureAlt,
		pictureId,
		pictureTitle,
		pictureCaption,
	} = attributes;

	function removePictureImg() {
		setAttributes({
			pictureUrl: undefined,
			pictureId: undefined,
			pictureCaption: undefined,
			pictureAlt: "",
		});
	}

	function updatePictureImg(image) {
		if (!image || !image.url) {
			removePictureImg();
		}
		setAttributes({
			pictureTitle: image.title,
			pictureUrl: image.url,
			pictureId: image.id,
			pictureAlt: image.alt,
			pictureCaption: image.caption,
		});
	}
	function onUploadError(message) {
		noticeOperations.removeAllNotices();
		noticeOperations.createErrorNotice(message);
	}

	function handleHasStickyLegend(hasStickyLegend) {
		setAttributes({ hasStickyLegend });
	}
	function handleHasFixedHeight(hasFixedHeight) {
		setAttributes({ hasFixedHeight });
	}
	function handleShowTitle(showTitle) {
		setAttributes({ showTitle });
	}
	function handleHasRoundedShadow(hasRoundedShadow) {
		setAttributes({ hasRoundedShadow });
	}
	function handleLegendLocationChange(legendLocation) {
		setAttributes({ legendLocation });
	}
	function handleHasLightbox(hasLightbox) {
		setAttributes({ hasLightbox });
	}

	const renderCaption = () => (
		<figcaption>
			{showTitle && pictureTitle && (
				<span className="figcaption-title">{pictureTitle}</span>
			)}{" "}
			{pictureCaption}
		</figcaption>
	);

	return (
		<>
			<InspectorControls>
				<PanelBody
					title="Paramètres"
					className="homegrade-blocks-components-image__panel-body "
				>
					<ToggleControl
						label="Légende Autocollante"
						checked={hasStickyLegend}
						onChange={handleHasStickyLegend}
						help="Coché, la légende sera ajouté sur un bandeau au dessus de l'image"
					/>
					<ToggleControl
						label="Hauteur de l'image Fixed"
						checked={hasFixedHeight}
						onChange={handleHasFixedHeight}
						help="Coché, la hauteur de l'image est fixe"
					/>
					<ToggleControl
						label="Afficher le titre"
						checked={showTitle}
						onChange={handleShowTitle}
					/>
					<ToggleControl
						label="Rounded & Shadow"
						checked={hasRoundedShadow}
						onChange={handleHasRoundedShadow}
					/>
					<ToggleControl
						label="Afficher une lightbox"
						checked={hasLightbox}
						onChange={handleHasLightbox}
					/>

					<ToggleGroupControl
						label="Emplacement de la légende"
						value="before"
						onChange={handleLegendLocationChange}
						isBlock
						__nextHasNoMarginBottom
					>
						<ToggleGroupControlOption value="before" label="Avant l'Image" />
						<ToggleGroupControlOption value="after" label="Après l'image" />
					</ToggleGroupControl>
				</PanelBody>
				<PanelBody
					title="Source de l'image"
					className="homegrade-blocks-components-image__panel-body "
				>
					{pictureUrl && <img src={pictureUrl} alt={pictureAlt} />}
					<div className="media-replace-container">
						<MediaReplaceFlow
							mediaId={pictureId}
							mediaUrl={pictureUrl}
							allowedTypes={["image"]}
							accept="image/*"
							onSelect={updatePictureImg}
							name={
								!pictureUrl
									? __("Ajouter", "homegrade-blocks__texte-backoffice")
									: __("Remplacer", "homegrade-blocks__texte-backoffice")
							}
						/>
						{pictureUrl && (
							<div>
								<Button
									className="custom-flow-button"
									variant="primary"
									icon={trash}
									label="Supprimer"
									onClick={removePictureImg}
								/>
							</div>
						)}
					</div>
					<Tip>
						<p>
							Le texte de votre Légende est automatiquement attribué depuis le
							champ "Légende" de votre image dans la gallerie des médias
						</p>
					</Tip>
				</PanelBody>
			</InspectorControls>
			<div>
				{pictureUrl && (
					<figure
						{...useBlockProps({
							className: `homegrade-blocks-labelled-picture homegrade-blocks-labelled-picture--legend-${
								hasStickyLegend ? "sticky" : "normal"
							}
							${hasFixedHeight ? "homegrade-blocks-labelled-picture--fixed-height" : ""} 
							${
								showTitle && pictureTitle
									? "homegrade-blocks-labelled-picture--legend-has-title"
									: ""
							}
						${hasRoundedShadow ? "homegrade-blocks-labelled-picture--rounded-shadow" : ""}`,
						})}
					>
						{legendLocation === "before" && renderCaption()}
						<img src={pictureUrl} alt={pictureAlt} />
						{legendLocation === "after" && renderCaption()}
					</figure>
				)}

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