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

const PIN_COLORS = [
	{ label: __('Blue', 'lead-gen'), value: 'blue' },
	{ label: __('Green', 'lead-gen'), value: 'green' },
	{ label: __('Light Blue', 'lead-gen'), value: 'lightblue' },
	{ label: __('Orange', 'lead-gen'), value: 'orange' },
	{ label: __('Pink', 'lead-gen'), value: 'pink' },
	{ label: __('Purple', 'lead-gen'), value: 'purple' },
	{ label: __('Red', 'lead-gen'), value: 'red' },
	{ label: __('Yellow', 'lead-gen'), value: 'yellow' },
];

const COLORS = [
	{ label: __('Primary', 'lead-gen'), value: 'primary' },
	{ label: __('Secondary', 'lead-gen'), value: 'secondary' },
	{ label: __('Accent 1', 'lead-gen'), value: 'accent-1' },
	{ label: __('Accent 2', 'lead-gen'), value: 'accent-2' },
]

const SIZES = [
	{ 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' },
	{ label: __('Full', 'lead-gen'), value: 'full' },
];

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		alignment,
		size = 'sm',
		staticImage = 0,
		markers = [],
		overrideZoom = false,
		zoom,
		lazyLoad = true,
		primary,
		secondary,
		pinColor,
		animationEntrance,
		animationDuration,
		animationDelay
	} = attributes;

	useEffect(() => {
		loadGoogleLibrary();
	}, []);

	const updateMarker = (index, key, value) => {
		const newMarkers = [...markers];

		if (key === null && typeof value === 'object') {
			newMarkers[index] = { ...newMarkers[index], ...value };
		} else {
			newMarkers[index] = { ...newMarkers[index], [key]: value };
		}

		setAttributes({ markers: newMarkers });
	};

	const addMarker = () => {
		setAttributes({
			markers: [
				...markers,
				{ place_id: '', address: '', lat: '', lng: '', title: '', description: '', area: false, radius: 1, show: false },
			],
		});
	};

	const removeMarker = (index) => {
		const newMarkers = [...markers];
		newMarkers.splice(index, 1);
		setAttributes({ markers: newMarkers });
	};

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Markers', 'lead-gen')} initialOpen={true}>
					{markers.length > 0 &&
						markers.map((marker, index) => (
							<MarkerItem
								key={index}
								marker={marker}
								index={index}
								updateMarker={updateMarker}
								removeMarker={removeMarker}
							/>
						))}

					<Button variant="primary" onClick={addMarker}>
						{__('Add Marker', 'lead-gen')}
					</Button>
				</PanelBody>

				<PanelBody title={__('Map Settings', 'lead-gen')} initialOpen={true}>
					<SelectControl
						label={__('Alignment', 'lead-gen')}
						value={alignment}
						options={[
							{ label: __('Left', 'lead-gen'), value: 'left' },
							{ label: __('Center', 'lead-gen'), value: 'center' },
							{ label: __('Right', 'lead-gen'), value: 'right' },
						]}
						onChange={(val) => setAttributes({ alignment: val })}
					/>

					<SelectControl
						label={__('Size', 'lead-gen')}
						help={__('Generated static maps are not supported for full width maps. An image must be provided if you select \'Full.\'', 'lead-gen')}
						value={size}
						options={SIZES}
						onChange={(val) => setAttributes({ size: val })}
					/>

					{size === 'full' && (
						<>
							<MediaUploadCheck>
								<MediaUpload
									onSelect={(media) => setAttributes({ staticImage: media?.id || null })}
									allowedTypes={['image']}
									value={staticImage}
									render={({ open }) => (
										<div className="upload-image">
											<Button onClick={open} variant="secondary">
												{staticImage ? __('Change Static Image', 'lead-gen') : __('Upload Static Image', 'lead-gen')}
											</Button>
											{staticImage ? (
												<Button onClick={() => setAttributes({ staticImage: 0 })} isDestructive variant="link">
													{__('Remove Image', 'lead-gen')}
												</Button>
											) : ''}
										</div>
									)}
								/>
							</MediaUploadCheck>
							{!staticImage && (
								<p>{__('WARNING: The map will not lazy-load if no placeholder image is provided. This may negatively impact page load and page speed scores.', 'lead-gen')}</p>
							)}
							<hr/>
						</>
					)}

					<ToggleControl
						label={__('Lazy Load', 'lead-gen')}
						help={__('The image will be displayed as the static placeholder. Clicking on it will load the map in its place.', 'lead-gen')}
						checked={lazyLoad}
						onChange={(val) => setAttributes({ lazyLoad: val })}
					/>

					<ToggleControl
						label={__('Override Zoom', 'lead-gen')}
						help={__('Check this to override the automatic zoom level on the map.', 'lead-gen')}
						checked={overrideZoom}
						onChange={(val) => setAttributes({ overrideZoom: val })}
					/>
					<p>{__('This is recommended when using a map with a single marker.', 'lead-gen')}</p>

					{overrideZoom && (
						<RangeControl
							label={__('Zoom', 'lead-gen')}
							value={zoom}
							onChange={(val) => setAttributes({ zoom: val })}
							min={1}
							max={20}
						/>
					)}
					<hr/>

					<SelectControl
						label={__('Primary Color', 'lead-gen')}
						value={primary}
						options={COLORS}
						onChange={(val) => setAttributes({ primary: val })}
					/>

					<SelectControl
						label={__('Secondary Color', 'lead-gen')}
						value={secondary}
						options={COLORS}
						onChange={(val) => setAttributes({ secondary: val })}
					/>

					<SelectControl
						label={__('Pin Color', 'lead-gen')}
						value={pinColor}
						options={PIN_COLORS}
						onChange={(val) => setAttributes({ pinColor: val })}
					/>

				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

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

export default Edit;
