import { __ } from '@wordpress/i18n';
import {
	PanelBody,
	TextControl,
	SelectControl,
	DropdownMenu,
	ToolbarGroup,
	ToolbarButton,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from '@wordpress/components';
import {
	InspectorControls,
	BlockControls,
	MediaReplaceFlow
} from '@wordpress/block-editor';
import { useEffect } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { registerFontAwesomeIcons } from '../components/icons/registerFontAwesome';
import {
	IconPicker,
	IconPickerToolbarButton,
	InlineIconPicker,
	Image,
	Link,
} from '@10up/block-components';
import {
	alignLeft,
	alignCenter,
	alignRight,
	alignJustify,
} from '@wordpress/icons';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ( { attributes, setAttributes } ) => {
	const {
		type = 'primary',
		link,
		alignment = 'left',
		size = 'md',
		icon,
		animationEntrance,
		animationDuration,
		animationDelay,
	} = attributes;

	const image = useSelect(
		(select) =>
			icon.type === 'upload' && icon.mediaId
				? select('core').getMedia(icon.mediaId)
				: null,
		[icon.mediaId]
	);

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

	useEffect(() => {
		if (icon.type === 'upload' && image && image.source_url && icon.url !== image.source_url) {
			setAttributes({
				icon: {
					...icon,
					url: image.source_url,
				}
			});
		}
	}, [image]);

	function handleImageSelect(image) {
		setAttributes({
			icon: {
				...icon,
				type: 'upload',
				mediaId: image.id,
				url: image.source_url,
				library: '',
				iconSet: '',
			}
		});
	}

	const handleLibraryIconSelect = (iconData) => {
		setAttributes({
			icon: {
				...icon,
				type: 'library',
				mediaId: null,
				url: '',
				library: iconData.name || '',
				iconSet: iconData.iconSet,
			}
		});
	};

	const handleLinkChange = ( newLink ) => {
		setAttributes({
			link: { ...link, url: newLink },
		});
	};

	const handleTypeChange = (newType) => {
		if (newType === 'none') {
			setAttributes({
				icon: {
					...icon,
					type: newType,
					mediaId: null,
					url: '',
					library: '',
					iconSet: '',
				}
			});
		} else {
			setAttributes({
				icon: {
					...icon,
					type: newType,
				}
			});
		}
	};

	const getAlignmentIcon = (alignment) => {
		switch (alignment) {
			case 'left':
				return alignLeft;
			case 'center':
				return alignCenter;
			case 'right':
				return alignRight;
			case 'justify':
				return alignJustify;
			default:
				return alignLeft;
		}
	};

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__accordion ${getVisibilityClasses( attributes )}`}
		>
			<BlockControls>
				<ToolbarGroup>
					{!icon.mediaId ? <IconPickerToolbarButton value={{ name: icon.library, iconSet: icon.iconSet }} onChange={(val) => handleLibraryIconSelect(val)} /> : null}
					<DropdownMenu
						icon={getAlignmentIcon(alignment)}
						label={__('Button Alignment', 'lead-gen')}
						popoverProps={{ position: 'bottom center' }}
						controls={[
							{
								icon: alignLeft,
								title: __('Align left', 'lead-gen'),
								isActive: alignment === 'left',
								onClick: () => setAttributes({ alignment: 'left' }),
							},
							{
								icon: alignCenter,
								title: __('Align center', 'lead-gen'),
								isActive: alignment === 'center',
								onClick: () => setAttributes({ alignment: 'center' }),
							},
							{
								icon: alignRight,
								title: __('Align right', 'lead-gen'),
								isActive: alignment === 'right',
								onClick: () => setAttributes({ alignment: 'right' }),
							},
							{
								icon: alignJustify,
								title: __('Justify', 'lead-gen'),
								isActive: alignment === 'justify',
								onClick: () => setAttributes({ alignment: 'justify' }),
							},
						]}
					/>
				</ToolbarGroup>
			</BlockControls>
			<InspectorControls>
				<PanelBody title={ __('Button Settings', 'lead-gen') } initialOpen={ true }>
					<TextControl
						label={ __('Button URL', 'lead-gen') }
						value={ link?.url || '' }
						onChange={ handleLinkChange }
						placeholder={ __('Enter URL', 'lead-gen') }
					/>
					<SelectControl
						label={ __('Button Type', 'lead-gen') }
						value={ type }
						options={[
							{ label: __('Primary', 'lead-gen'), value: 'primary' },
							{ label: __('Secondary', 'lead-gen'), value: 'secondary' },
							{ label: __('Tertiary', 'lead-gen'), value: 'tertiary' },
							{ label: __('Link', 'lead-gen'), value: 'link' },
						]}
						onChange={(val) => setAttributes({ type: val })}
					/>
					<ToggleGroupControl
						label={ __('Button Size', 'lead-gen') }
						value={size}
						isBlock
						__nextHasNoMarginBottom
						__next40pxDefaultSize
						onChange={(val) => setAttributes({ size: val })}
					>
						<ToggleGroupControlOption value="xs" label="XS" />
						<ToggleGroupControlOption value="sm" label="SM" />
						<ToggleGroupControlOption value="md" label="MD" />
						<ToggleGroupControlOption value="lg" label="LG" />
						<ToggleGroupControlOption value="xl" label="XL" />
					</ToggleGroupControl>
					<ToggleGroupControl
						label={ __('Icon Type', 'lead-gen') }
						value={icon.type}
						isBlock
						__nextHasNoMarginBottom
						__next40pxDefaultSize
						onChange={(val) => handleTypeChange(val)}
					>
						<ToggleGroupControlOption value="none" label="None" />
						<ToggleGroupControlOption value="upload" label="Upload" />
						<ToggleGroupControlOption value="library" label="Library" />
					</ToggleGroupControl>
					{icon.type === 'upload' && (
						<>
							{icon.mediaId && (
								<BlockControls group="inline">
									<ToolbarGroup>
										<MediaReplaceFlow
											mediaId={icon.mediaId}
											allowedTypes={['image']}
											accept="image/*"
											onSelect={handleImageSelect}
										/>
										<ToolbarButton
											onClick={() => setAttributes({ icon: { mediaId: null, url: null } })}
											icon="trash"
											label={__('Remove Icon', 'lead-gen')}
										/>
									</ToolbarGroup>
								</BlockControls>
							)}
							<Image
								id={icon.mediaId || null}
								size="full"
								onSelect={handleImageSelect}
								focalPoint={false}
								allowedTypes={['image/svg+xml']}
								canEditImage={true}
								labels={{
									title: 'Select SVG Image',
									instructions: 'Upload a SVG or pick one from your media library.'
								}}
							/>
						</>
					)}
					{icon.type === 'library' && (
						<IconPicker value={{ name: icon.library, iconSet: icon.iconSet }} onChange={(val) => handleLibraryIconSelect(val)} />
					)}
					{(icon.type === 'library' || icon.type === 'upload') && (
						<ToggleGroupControl
							label={ __('Icon Position', 'lead-gen') }
							value={icon?.position || 'before'}
							isBlock
							__nextHasNoMarginBottom
							__next40pxDefaultSize
							onChange={(pos) => setAttributes({ icon: { ...icon, position: pos } })}
						>
							<ToggleGroupControlOption value="before" label="Before" />
							<ToggleGroupControlOption value="after" label="After" />
						</ToggleGroupControl>
					)}
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>
			<div className="lg-block lg-block__button">
				<span
					href={link?.url}
					className={`btn btn-${type} btn-${size} btn-${alignment} btn-icon-${icon?.position}`}
					target={link?.opensInNewTab ? '_blank' : null}
				>
					{icon.type !== 'none' && (
						<span className="btn-icon">
							{icon.type === 'upload' && icon.url && (
								<img
									src={icon.url}
									alt=""
									style={{ width: '1em', height: '1em' }}
								/>
							)}
							{icon.type === 'library' && icon.library && icon.iconSet && (
								<InlineIconPicker value={{ name: icon.library, iconSet: icon.iconSet }} onChange={(val) => handleLibraryIconSelect(val)} />
							)}
						</span>
					)}
					<Link
						tagName="span"
						value={link.text}
						url={link.url}
						opensInNewTab={link?.opensInNewTab || false}
						onTextChange={(val) => setAttributes({ link: { ...link, text: val } })}
						onLinkChange={(val) => setAttributes({ link: { ...link, url: val?.url, text: val?.title } })}
						onLinkRemove={() => setAttributes({ link: { ...link, url: null, opensInNewTab: null } })}
						className="btn-text"
						placeholder="Button Text"
						allowedFormats={['core/bold', 'core/italic']}
					/>
				</span>
			</div>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
