import { __ } from "@wordpress/i18n";
import "./editor.scss";
import "./timeline-step";

import {
	useBlockProps,
	RichText,
	InnerBlocks,
	InspectorControls,
	MediaReplaceFlow,
	MediaPlaceholder,
	BlockControls,
} from "@wordpress/block-editor";

import { useEffect } from "@wordpress/element";
import { useSelect, dispatch } from "@wordpress/data";
import {
	PanelBody,
	PanelRow,
	Button,
	RadioControl,
	ToggleControl,
	ToolbarGroup,
	ToolbarButton,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from "@wordpress/components";
import { trash } from "@wordpress/icons";
import {
	headingLevel1,
	headingLevel2,
	headingLevel3,
	headingLevel4,
	headingLevel5,
} from "@wordpress/icons";

export default function Edit({ attributes, setAttributes, clientId }) {
	let {
		hasStepPictures,
		lateralPicturesFormat,
		hasStepIcons,
		hasLateralCover,
		lateralCoverId,
		lateralCoverAlt,
		lateralCoverUrl,
		lateralCoverDescription,
		lateralCoverCaption,
		blockTitle,
		blockSubtitle,
		hasTitle,
		headingLevel,
	} = attributes;

	let children = useSelect(
		(select) =>
			select("core/block-editor").getBlocksByClientId(clientId)[0].innerBlocks
	);

	function onChangeBlockTitle(blockTitle) {
		setAttributes({ blockTitle });
	}
	function onChangeBlockSubtitle(blockSubtitle) {
		setAttributes({ blockSubtitle });
	}
	function onChangeHeadingLevel(newHeadingLevel) {
		setAttributes({ headingLevel: newHeadingLevel });
	}

	function onChangeImagesDispositionType(disposition) {
		if (disposition === "hasStepPictures") {
			setAttributes({ hasStepPictures: true, hasLateralCover: false });
			removeLateralCoverAttributes();
		}
		if (disposition === "hasLateralCover") {
			setAttributes({ hasStepPictures: false, hasLateralCover: true });
		}
	}
	function handlelateralPicturesFormatChange(lateralPicturesFormat) {
		setAttributes({ lateralPicturesFormat });
	}
	function onChangehasStepIcons() {
		setAttributes({ hasStepIcons: !hasStepIcons });
	}
	function onChangeHasTitle(newHasTitle) {
		setAttributes({ hasTitle: !hasTitle });
		if (!newHasTitle) {
			setAttributes({ blockTitle: "", blockSubtitle: "" });
		}
	}

	function setLateralCoverAttributes(cover) {
		setAttributes({
			lateralCoverId: cover.id,
			lateralCoverAlt: cover.alt,
			lateralCoverUrl: cover.url,
			lateralCoverCaption: cover?.caption,
			lateralCoverDescription: cover?.description,
		});
	}
	function removeLateralCoverAttributes() {
		setAttributes({
			lateralCoverId: null,
			lateralCoverAlt: null,
			lateralCoverUrl: null,
			lateralCoverCaption: null,
			lateralCoverDescription: null,
		});
	}

	function updateChildrensProps(children) {
		children.forEach((child) => {
			dispatch("core/block-editor").updateBlockAttributes(child.clientId, {
				hasStepIcon: hasStepIcons,
				hasStepPicture: hasStepPictures,
			});
		});
	}

	useEffect(() => {
		if (children && children.length > 0) {
			updateChildrensProps(children);
		}
	}, [children, hasStepPictures, hasStepIcons]);

	const TEMPLATE = [
		[
			"homegrade-content-blocks/timeline-step",
			{
				timelineStepTitle: "Etape 1",
				timelineStepSubtitle: "sous titre",
			},
		],
		[
			"homegrade-content-blocks/timeline-step",
			{
				timelineStepTitle: "Etape 2",
				timelineStepSubtitle: "sous titre",
			},
		],
	];

	return (
		<>
			<InspectorControls>
				<PanelBody
					title={__("Variantes de Timeline", "homegrade-blocks")}
					className={
						"homegrade-blocks-timeline__panel-body homegrade-blocks-components-image__panel-body"
					}
				>
					<PanelRow>
						<ToggleControl
							label={__("Titre de bloc", "homegrade-blocks")}
							help={
								hasTitle ? "Titre de bloc." : "Ne pas afficher de bloc titrage"
							}
							checked={hasTitle}
							onChange={onChangeHasTitle}
						/>
					</PanelRow>
					<PanelRow>
						<ToggleControl
							label={__("Icones", "homegrade-blocks__texte-backoffice")}
							help={
								hasStepIcons
									? "Afficher des icones pour chaque ligne"
									: "Ne pas afficher d'icones"
							}
							checked={hasStepIcons}
							onChange={onChangehasStepIcons}
						/>
					</PanelRow>

					<PanelRow>
						<ToggleGroupControl
							label="Type d'image Latérale"
							className="homegrade-blocks-components-image__ratio-selector"
							isBlock
							onChange={onChangeImagesDispositionType}
							value={hasStepPictures ? "hasStepPictures" : "hasLateralCover"}
						>
							<ToggleGroupControlOption
								variant="hasStepPictures"
								label="image par ligne de timeline"
								value="hasStepPictures"
							/>
							<ToggleGroupControlOption
								variant="lateralCover"
								label=" Image latérale unique"
								value="hasLateralCover"
							/>
						</ToggleGroupControl>
					</PanelRow>

					<PanelRow>
						<RadioControl
							label={__("Format d'image(s) latérale(s)", "textdomain")}
							selected={lateralPicturesFormat}
							options={[
								{ label: "Carré", value: "squared" },
								{ label: "Moyenne", value: "md" },
								{ label: "Hauteur originale", value: "xl" },
								{ label: "Illustration", value: "illustration" },
							]}
							onChange={handlelateralPicturesFormatChange}
						/>
					</PanelRow>

					{lateralCoverUrl && (
						<img src={lateralCoverUrl} alt={lateralCoverAlt} />
					)}

					{hasLateralCover && (
						<div className="media-replace-container">
							<MediaReplaceFlow
								mediaId={lateralCoverId}
								mediaUrl={lateralCoverUrl}
								allowedTypes={["image"]}
								accept="image/*"
								onSelect={setLateralCoverAttributes}
								name={
									!lateralCoverUrl
										? __("Ajouter", "homegrade-blocks__texte-backoffice")
										: __("Remplacer", "homegrade-blocks__texte-backoffice")
								}
							/>
							{lateralCoverUrl && (
								<>
									<Button
										className="custom-flow-button"
										variant="primary"
										icon={trash}
										label="Supprimer"
										onClick={removeLateralCoverAttributes}
									/>
								</>
							)}
						</div>
					)}
				</PanelBody>
			</InspectorControls>
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						isActive={headingLevel === "h1"}
						icon={headingLevel1}
						onClick={() => {
							onChangeHeadingLevel("h1");
						}}
					/>
					<ToolbarButton
						isActive={headingLevel === "h2"}
						icon={headingLevel2}
						onClick={() => {
							onChangeHeadingLevel("h2");
						}}
					/>
					<ToolbarButton
						isActive={headingLevel === "h3"}
						icon={headingLevel3}
						onClick={() => {
							onChangeHeadingLevel("h3");
						}}
					/>
					<ToolbarButton
						isActive={headingLevel === "h4"}
						icon={headingLevel4}
						onClick={() => {
							onChangeHeadingLevel("h4");
						}}
					/>
					<ToolbarButton
						isActive={headingLevel === "h5"}
						icon={headingLevel5}
						onClick={() => {
							onChangeHeadingLevel("h5");
						}}
					/>
				</ToolbarGroup>
			</BlockControls>
			<section
				{...useBlockProps({
					className: `homegrade-blocks-timeline ${
						hasStepIcons ? "homegrade-blocks-timeline--has-step-icons" : ""
					}
					${hasLateralCover ? "homegrade-blocks-timeline--has-lateral-cover" : ""}`,
				})}
			>
				<div className="section_titling section_titling--center">
					{hasTitle && (
						<>
							<RichText
								value={blockTitle}
								tagName={headingLevel}
								className="section_titling__title"
								placeholder={__(
									"Ajouter ici le Titre de la liste de membres",
									"homegrade"
								)}
								onChange={onChangeBlockTitle}
							/>
							<RichText
								value={blockSubtitle}
								tagName="p"
								className="section_titling__subtitle"
								placeholder={__(
									"Ajouter ici le Sous-titre de la liste de membres",
									"homegrade"
								)}
								onChange={onChangeBlockSubtitle}
							/>
						</>
					)}
				</div>

				<div className="homegrade-blocks-timeline__container">
					{hasLateralCover && !lateralCoverUrl && (
						<MediaPlaceholder
							accept="image/*"
							allowedTypes={["image"]}
							onSelect={setLateralCoverAttributes}
							multiple={false}
							handleUpload={true}
						/>
					)}

					{hasLateralCover && lateralCoverUrl && (
						<figure
							className={`homegrade-blocks-timeline__lateral-cover homegrade-blocks-timeline__lateral-cover--${lateralPicturesFormat}`}
						>
							<img src={lateralCoverUrl} alt={lateralCoverAlt} />

							{(lateralCoverDescription || lateralCoverCaption) && (
								<figcaption>
									{lateralCoverDescription && (
										<p className="description">{lateralCoverDescription}</p>
									)}
									{lateralCoverCaption && (
										<p className="caption">{lateralCoverCaption}</p>
									)}
								</figcaption>
							)}
						</figure>
					)}
					<InnerBlocks
						allowedBlocks={["homegrade-content-blocks/timeline-step"]}
						template={TEMPLATE}
					/>
				</div>
			</section>
		</>
	);
}
