import { __ } from "@wordpress/i18n";
import {
	useBlockProps,
	RichText,
	InnerBlocks,
	InspectorControls,
	MediaUpload,
	MediaUploadCheck,
} from "@wordpress/block-editor";
import "./editor.scss";
import { PanelBody, TextControl, Button } from "@wordpress/components";

export default function Edit({ attributes, setAttributes }) {
	const { title, iconId, iconUrl } = attributes;

	const blockProps = useBlockProps({
		className: "block-chapo",
	});

	return (
		<>
			<InspectorControls>
				<PanelBody title={__("Tab", "carhop-blocks")}>
					<TextControl
						label={__("Titre", "carhop-blocks")}
						value={title}
						onChange={(value) => setAttributes({ title: value })}
					/>
				</PanelBody>
				<PanelBody title={__("Icône", "carhop-blocks")}>
					<MediaUploadCheck>
						<MediaUpload
							onSelect={(media) =>
								setAttributes({
									iconId: media.id,
									iconUrl: media.url,
								})
							}
							allowedTypes={["image"]}
							value={iconId}
							render={({ open }) => (
								<>
									{iconUrl ? (
										<div className="tab__icon-preview">
											<img
												src={iconUrl}
												alt=""
												style={{ maxWidth: 48, height: "auto" }}
											/>
											<div style={{ marginTop: 8 }}>
												<Button
													variant="secondary"
													onClick={open}
													style={{ marginRight: 8 }}
												>
													{__("Remplacer", "carhop-blocks")}
												</Button>
												<Button
													variant="tertiary"
													isDestructive
													onClick={() =>
														setAttributes({ iconId: 0, iconUrl: "" })
													}
												>
													{__("Supprimer", "carhop-blocks")}
												</Button>
											</div>
										</div>
									) : (
										<Button variant="secondary" onClick={open}>
											{__("Choisir une image", "carhop-blocks")}
										</Button>
									)}
								</>
							)}
						/>
					</MediaUploadCheck>
				</PanelBody>
			</InspectorControls>
			<div {...blockProps}>
				<InnerBlocks
					allowedBlocks={[
						"core/heading",
						"core/paragraph",
						"core/list",
						"core/button",
						"core/buttons",
						"core/image",
						"core/embed",
						"core/quote",
						"core/pullquote",
						"core/media-text",
						"core/table",
						"core/group",
						"core/columns",
						"core/post-title",
						"carhop-blocks/cta",
						"carhop-blocks/heading",
						"carhop-blocks/cta-group",
						"carhop-blocks/audio-player",
						"carhop-blocks/content-box",
						"carhop-blocks/content-card",
						"carhop-blocks/notice-panel",
						"shortcode",
					]}
					template={[
						["core/heading", { content: "Titre", level: 3 }],
						["core/paragraph", { content: "Contenu" }],
					]}
				/>
			</div>
		</>
	);
}
