import { __ } from '@wordpress/i18n';
import { InspectorControls, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { useEffect, useRef } from '@wordpress/element';
import { Button, PanelBody, ToggleControl, RangeControl, SelectControl } from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { initGallery } from "./script";
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const SPACING_OPTIONS = [
	{ label: __('Extra Small', 'lead-gen'), value: 'xs' },
	{ label: __('Small', 'lead-gen'), value: 'sm' },
	{ label: __('Medium', 'lead-gen'), value: 'md' },
	{ label: __('Large', 'lead-gen'), value: 'lg' },
	{ label: __('Extra Large', 'lead-gen'), value: 'xl' },
];

const BUTTON_STYLE_OPTIONS = [
	{ label: __('Primary', 'lead-gen'), value: 'primary' },
	{ label: __('Secondary', 'lead-gen'), value: 'secondary' },
];

const ASPECT_RATIO_OPTIONS = [
	{ label: '16:9', value: '16-9' },
	{ label: '9:16', value: '9-16' },
	{ label: '1:1', value: '1-1' },
	{ label: '4:3', value: '4-3' },
	{ label: '3:4', value: '3-4' },
	{ label: '21:9', value: '21-9' },
	{ label: '9:21', value: '9-21' },
];

const IMAGE_SIZE_OPTIONS = [
	{ label: 'thumbnail', value: 'thumbnail' },
	{ label: 'medium', value: 'medium' },
	{ label: 'medium_large', value: 'medium_large' },
	{ label: 'large', value: 'large' },
	{ label: '1536x1536', value: '1536x1536' },
	{ label: '2048x2048', value: '2048x2048' },
	{ label: 'gform-image-choice-sm', value: 'gform-image-choice-sm' },
	{ label: 'gform-image-choice-md', value: 'gform-image-choice-md' },
	{ label: 'gform-image-choice-lg', value: 'gform-image-choice-lg' },
];

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		gallery = [],
		layout = 'grid',
		columns,
		spacing,
		aspectRatio,
		imageSize,
		sorting = false,
		buttonStyle,
		lightbox,
		showTitle,
		showDesc,
		animationEntrance,
		animationDuration,
		animationDelay
	} = attributes;

	const wrapperRef = useRef(null);

	useEffect(() => {
		if (layout !== 'masonry') return;
		if (!wrapperRef.current) return;

		const observer = new MutationObserver(() => {
			const galleryEl = wrapperRef.current.querySelector('.lg-block__gallery--native');
			if (galleryEl) {
				initGallery(galleryEl);
			}
		});

		observer.observe(wrapperRef.current, {
			childList: true,
			subtree: true,
		});

		return () => observer.disconnect();
	}, [layout]);

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Gallery Settings', 'lead-gen')} initialOpen={true}>
					<MediaUploadCheck>
						<MediaUpload
							onSelect={(images) =>
								setAttributes({ gallery: images.map((img) => img.id) })
							}
							allowedTypes={['image']}
							multiple
							gallery
							value={gallery}
							render={({ open }) => (
								<div className="upload-image">
									<Button onClick={open} variant="secondary">
										{gallery?.length ? __('Edit Images', 'lead-gen') : __('Select Images', 'lead-gen')}
									</Button>
									{gallery?.length ? (
										<Button onClick={() => setAttributes({ gallery: [] })} isDestructive variant="link">
											{__('Remove Images', 'lead-gen')}
										</Button>
									) : ''}
								</div>
							)}
						/>
					</MediaUploadCheck>
					<hr/>
					<SelectControl
						label={__('Layout', 'lead-gen')}
						value={layout}
						options={[
							{ label: __('Grid', 'lead-gen'), value: 'grid' },
							{ label: __('Masonry', 'lead-gen'), value: 'masonry' },

						]}
						onChange={(val) => setAttributes({ layout: val })}
					/>
					<RangeControl
						label={__('Columns', 'lead-gen')}
						value={columns}
						onChange={(val) => setAttributes({ columns: val })}
						min={1}
						max={6}
					/>
					<SelectControl
						label={__('Spacing', 'lead-gen')}
						value={spacing}
						options={SPACING_OPTIONS}
						onChange={(value) => setAttributes({ spacing: value })}
					/>
					<SelectControl
						label={__('Aspect Ratio', 'lead-gen')}
						value={aspectRatio}
						options={ASPECT_RATIO_OPTIONS}
						onChange={(value) => setAttributes({ aspectRatio: value })}
					/>
					<SelectControl
						label={__('Image Size', 'lead-gen')}
						value={imageSize}
						options={IMAGE_SIZE_OPTIONS}
						onChange={(value) => setAttributes({ imageSize: value })}
					/>
					<ToggleControl
						label={__('Lightbox', 'lead-gen')}
						help={__('Open the image in a lightbox?', 'lead-gen')}
						checked={lightbox}
						onChange={(val) => setAttributes({ lightbox: val })}
					/>
					<ToggleControl
						label={__('Image Title', 'lead-gen')}
						help={__('Show the Image Title', 'lead-gen')}
						checked={showTitle}
						onChange={(val) => setAttributes({ showTitle: val })}
					/>
					<ToggleControl
						label={__('Image Description', 'lead-gen')}
						help={__('Show the Image Description', 'lead-gen')}
						checked={showDesc}
						onChange={(val) => setAttributes({ showDesc: val })}
					/>
					<ToggleControl
						label={__('Category Sorting', 'lead-gen')}
						help={__('Enables Category-Sorting Buttons', 'lead-gen')}
						checked={sorting}
						onChange={(val) => setAttributes({ sorting: val })}
					/>
					{sorting && (
						<SelectControl
							label={__('Button Style', 'lead-gen')}
							value={buttonStyle}
							options={BUTTON_STYLE_OPTIONS}
							onChange={(value) => setAttributes({ buttonStyle: value })}
						/>
					)}
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			<div ref={wrapperRef}>
				<ServerSideRender block={name} attributes={attributes} />
			</div>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
