import { __ } from "@wordpress/i18n";
import "./editor.scss";
import { useSelect } from "@wordpress/data";
import {
	InnerBlocks,
	useBlockProps,
	RichText,
	MediaReplaceFlow,
	InspectorControls,
	__experimentalLinkControl as LinkControl,
	MediaPlaceholder,
} from "@wordpress/block-editor";

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

import { lock, trash } from "@wordpress/icons";

export default function Edit({ attributes, setAttributes }) {
	const {
		hasCta,
		cta,
		hasCustomImage,
		imageId,
		imageAlt,
		imageUrl,
		coverSize,
	} = attributes;

	const pageIllustration = useSelect((select) => {
		const currentPost = select("core/editor").getCurrentPost();
		if (currentPost && currentPost.acf && currentPost.acf.page_illustration) {
			let Image = select("core").getMedia(currentPost.acf.page_illustration);
			return Image;
		}
	});

	function onChangeHasCustomImage(newHasAutoImage) {
		setAttributes({ hasCustomImage: !hasCustomImage });
		if (!newHasAutoImage) {
			removeImageAttributes();
		}
	}
	function setImageAttributes(image) {
		setAttributes({
			imageId: image.id,
			imageAlt: image.alt,
			imageUrl: image.url,
		});
	}
	function removeImageAttributes() {
		setAttributes({
			imageId: null,
			imageAlt: null,
			imageUrl: null,
		});
	}
	function onChangeHasCta(newHasCta) {
		setAttributes({ hasCta: !hasCta });
		if (!newHasCta) {
			setAttributes({ cta: undefined });
		}
	}
	function onChangeCTA(newCtaValue) {
		setAttributes({
			cta: {
				title: !cta || !cta.title ? newCtaValue.title : cta.title,
				id: newCtaValue.id,
				kind: newCtaValue.kind,
				type: newCtaValue.type,
				url: newCtaValue.url,
			},
		});
	}
	function onChangeTextControl(newCtaTitle) {
		setAttributes({
			cta: {
				...cta,
				title: newCtaTitle,
			},
		});
	}
	function onCoverSizeChange(coverSize) {
		setAttributes({ coverSize });
	}
	return (
		<>
			<InspectorControls>
				<PanelBody
					className="homegrade-blocks-components-image__panel-body"
					title={__("Image d'accompagnement", "homegrade-blocks")}
				>
					<ToggleControl
						label="Couverture automatique"
						checked={!hasCustomImage}
						onChange={onChangeHasCustomImage}
					/>
					{!hasCustomImage && (
						<Tip>
							La couverture est automatiquement généré à partir de
							l'illustration de couverture de la page.
						</Tip>
					)}
					{hasCustomImage && (
						<>
							{imageUrl && <img src={imageUrl} alt={imageAlt} />}
							<div className="media-replace-container">
								<MediaReplaceFlow
									mediaId={imageId}
									mediaUrl={imageUrl}
									allowedTypes={["image"]}
									accept="image/*"
									onSelect={setImageAttributes}
									name={
										!imageUrl
											? __(
													"Ajouter votre image manuellement",
													"homegrade-blocks",
											  )
											: __("Remplacer", "homegrade-blocks")
									}
								/>
								{imageUrl && (
									<>
										<Button
											className="custom-flow-button"
											variant="primary"
											icon={trash}
											label="Supprimer"
											onClick={removeImageAttributes}
										/>
									</>
								)}
							</div>
						</>
					)}
					<ToggleGroupControl
						className="homegrade-blocks-highlight__variant"
						isBlock
						label="Taille de la couverture"
						onChange={onCoverSizeChange}
						value={coverSize}
					>
						<ToggleGroupControlOption label="Small" value="small" />
						<ToggleGroupControlOption label="Medium" value="medium" />
						<ToggleGroupControlOption label="Large" value="large" />
					</ToggleGroupControl>
				</PanelBody>

				<PanelBody
					className="homegrade-blocks-content-page-header__panel-cta"
					title={__("Call to action", "homegrade-blocks")}
				>
					<ToggleControl
						label="Afficher un call to action"
						checked={hasCta}
						onChange={onChangeHasCta}
					/>

					{hasCta && (
						<>
							<TextControl
								label="Titre du cta"
								value={cta && cta.title ? cta.title : ""}
								onChange={onChangeTextControl}
							/>
							<LinkControl
								label="Lien du cta"
								title={__("Call to action", "homegrade-blocks")}
								value={cta}
								onChange={onChangeCTA}
							/>
						</>
					)}
				</PanelBody>
			</InspectorControls>
			<section
				{...useBlockProps({
					className: `homegrade-blocks-content-page-header block-content-page-header`,
				})}
			>
				<div class="block-content-page-header__content">
					<InnerBlocks
						template={[
							["homegrade-content-blocks/section-titling", { lock: true }],
							["core/paragraph", { placeholder: "Ajouter ici le texte" }],
						]}
						allowedBlocks={[
							"core/paragraph",
							"core/list",
							"core/button",
							"core/buttons",
							"gravityforms/form",
							"homegrade-content-blocks/section-titling",
							"acf/search-artisan-btn",
						]}
					/>
					{cta && cta.title && cta.url && <a href={cta.url}>{cta.title}</a>}
				</div>
				{pageIllustration && !hasCustomImage && (
					<img
						className="block-content-page-header__page-icon"
						src={pageIllustration.source_url}
						alt=""
					/>
				)}
				{hasCustomImage && imageUrl && (
					<img
						src={imageUrl}
						alt={imageAlt}
						className={`block-content-page-header__page-icon block-content-page-header__page-icon--${coverSize}`}
					/>
				)}
				{hasCustomImage && !imageUrl && (
					<MediaPlaceholder
						accept="image/*"
						allowedTypes={["image"]}
						onSelect={setImageAttributes}
						multiple={false}
						handleUpload={true}
					/>
				)}
			</section>
		</>
	);
}
