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,
	ToggleControl,
	Button,
	Tip,
} from "@wordpress/components";

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

export default function Edit({ attributes, setAttributes }) {
	const {
		anchor,
		blockCustomTitle,
		hasCustomTitle,
		pageHeaderTitle,
		pageHeaderDescription,
		hasCta,
		cta,
		hasCustomImage,
		imageId,
		imageAlt,
		imageUrl,
	} = attributes;

	const pageTitle = useSelect((select) => {
		const { getEditedPostAttribute } = select("core/editor");
		return getEditedPostAttribute("title");
	});

	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;
		}
	});

	console.log("pageIllustration", pageIllustration);

	function onChangeBlockCustomTitle(blockCustomTitle) {
		setAttributes({ blockCustomTitle });
	}
	function onChangeTitle(newTitle) {
		setAttributes({ pageHeaderTitle: newTitle });
	}
	function onChangeHasCustomTitle(newHasAutoTitle) {
		setAttributes({ hasCustomTitle: !hasCustomTitle });
		if (newHasAutoTitle) {
			setAttributes({ blockCustomTitle: undefined });
		}
	}
	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 onChangeDescription(newDescription) {
		setAttributes({ pageHeaderDescription: newDescription });
	}
	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,
			},
		});
	}
	console.log("attributes", attributes);
	return (
		<>
			<InspectorControls>
				<PanelBody
					className="homegrade-blocks-content-page-header__panel-cta"
					title={__("Titre du bloc", "homegrade-blocks")}
				>
					<ToggleControl
						label="Titre automatique"
						checked={!hasCustomTitle}
						onChange={onChangeHasCustomTitle}
					/>
					{!hasCustomTitle && (
						<Tip>
							Le titre est automatiquement généré à partir du titre de la page
						</Tip>
					)}
				</PanelBody>
				<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>
						</>
					)}
				</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">
					<div className="section_titling section_titling--left">
						{!hasCustomTitle && (
							<h1 className="section_titling__title">{pageTitle}</h1>
						)}
						{hasCustomTitle && (
							<RichText
								className="section_titling__title"
								tagName="h1"
								placeholder={__(
									"Ajouter ici le Titre du Bloc Header",
									"homegrade"
								)}
								value={blockCustomTitle}
								onChange={onChangeBlockCustomTitle}
							/>
						)}

						<RichText
							className="section_titling__subtitle"
							tagName="h2"
							placeholder={__(
								"Ajouter ici le Titre du Bloc Header",
								"homegrade"
							)}
							value={pageHeaderTitle}
							onChange={onChangeTitle}
							// style={{ textAlign: props.attributes.alignment }}
						/>
					</div>
					<RichText
						tagName="p"
						placeholder={__(
							"Ajouter ici le texte d'introduction de cette page",
							"homegrade"
						)}
						value={pageHeaderDescription}
						onChange={onChangeDescription}
						// style={{ textAlign: props.attributes.alignment }}
					/>
					<InnerBlocks
						template={[
							["core/paragraph", { placeholder: "Ajouter ici le texte" }],
						]}
						allowedBlocks={[
							"core/paragraph",
							"core/list",
							"core/button",
							"core/buttons",
							"gravityforms/form",
							"homegrade-content-blocks/section-titling",
						]}
					/>
					{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"
					/>
				)}
				{hasCustomImage && !imageUrl && (
					<MediaPlaceholder
						accept="image/*"
						allowedTypes={["image"]}
						onSelect={setImageAttributes}
						multiple={false}
						handleUpload={true}
					/>
				)}
			</section>
		</>
	);
}
