import { __ } from "@wordpress/i18n";
import "./editor.scss";
import ImageMediaPlaceholder from "../../_components/ImageMediaPlaceholder";
import Image from "../../_components/Image";
import ImagePanelBody from "../../_components/ImagePanelBody";
import {
	InspectorControls,
	useBlockProps,
	InnerBlocks,
	MediaPlaceholder,
	MediaReplaceFlow,
} from "@wordpress/block-editor";
import { PanelBody, Button } from "@wordpress/components";
import { trash } from "@wordpress/icons";
import { PanelRow, ToggleControl } from "@wordpress/components";
export default function Edit({ attributes, setAttributes }) {
	let { iconUrl, iconAlt, iconId, hasShadow } = attributes;
	function setIconAttributes(icon) {
		setAttributes({
			iconId: icon.id,
			iconAlt: icon.alt,
			iconUrl: icon.url,
		});
	}

	function removeIconAttributes() {
		setAttributes({
			iconId: null,
			iconAlt: null,
			iconUrl: null,
		});
	}

	function onHasShadowChange() {
		setAttributes({ hasShadow: !hasShadow });
	}

	return (
		<>
			<InspectorControls>
				<PanelBody
					className="homegrade-blocks-components-image__panel-body homegrade-blocks-components-icon__panel-body"
					title={__("Icone", "homegrade-blocks")}
				>
					{iconUrl && (
						<img className="icon-preview" src={iconUrl} alt={iconAlt} />
					)}
					<div className="media-replace-container">
						<MediaReplaceFlow
							label={__("Source", "homegrade-blocks")}
							mediaId={iconId}
							mediaUrl={iconUrl}
							allowedTypes={["image"]}
							accept="image/*"
							onSelect={setIconAttributes}
							name={
								!iconUrl
									? __("Ajouter", "homegrade-blocks")
									: __("Remplacer", "homegrade-blocks")
							}
						/>
						{iconUrl && (
							<>
								<Button
									className="custom-flow-button"
									variant="primary"
									icon={trash}
									label="Supprimer"
									onClick={removeIconAttributes}
								/>
							</>
						)}
					</div>

					<PanelRow>
						<ToggleControl
							label={__("Ombre", "homegrade-blocks")}
							checked={hasShadow}
							onChange={onHasShadowChange}
						/>
					</PanelRow>
				</PanelBody>
			</InspectorControls>
			{!iconUrl && (
				<MediaPlaceholder
					accept="image/*"
					allowedTypes={["image"]}
					onSelect={setIconAttributes}
					multiple={false}
					handleUpload={true}
				/>
			)}
			<div
				{...useBlockProps({
					className: `homegrade-blocks-icon ${
						hasShadow
							? "homegrade-blocks-icon--has-shadow"
							: "homegrade-blocks-icon--no-shadow"
					} `,
				})}
			>
				{iconUrl && <img src={iconUrl} alt={iconAlt} />}
			</div>
		</>
	);
}
