import { __ } from '@wordpress/i18n';
import {
	InspectorControls,
	MediaReplaceFlow,
} from '@wordpress/block-editor';
import {
	PanelBody,
	ToolbarGroup,
	ToolbarButton,
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEffect } from '@wordpress/element';
import {
	IconPicker,
	InlineIconPicker,
	Image,
} from '@10up/block-components';

import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { registerFontAwesomeIcons } from '../components/icons/registerFontAwesome';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const DEFAULT_ICON = {
	type: 'library',
	mediaId: 0,
	url: '',
	library: 'star',
	iconSet: 'fontawesome/solid',
	title: 'Star'
};

const Edit = ({ attributes, setAttributes }) => {
	const {
		icon,
		iconDisplay = 'decorative',
		animationEntrance,
		animationDuration,
		animationDelay,
		anchor,
	} = attributes;

	useEffect(() => {
		registerFontAwesomeIcons();
		if (icon.type === 'none') {
			setAttributes({
				icon: DEFAULT_ICON
			});
		}
	}, []);

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

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

	const handleTypeChange = (newType) => {
		if (newType === 'none') {
			setAttributes({ icon: DEFAULT_ICON });
		} else {
			setAttributes({ icon: { ...icon, type: newType } });
		}
	};

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

	const handleImageSelect = (image) => {
		setAttributes({
			icon: {
				type: 'upload',
				mediaId: image.id,
				url: image.source_url,
				library: '',
				iconSet: '',
				title: image.title || '',
			}
		});
	};

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__icon ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Icon Settings', 'lead-gen')} initialOpen={true}>
					<ToggleGroupControl
						label={__('Icon Type', 'lead-gen')}
						value={icon.type}
						isBlock
						onChange={handleTypeChange}
					>
						<ToggleGroupControlOption value="upload" label="Upload" />
						<ToggleGroupControlOption value="library" label="Library" />
					</ToggleGroupControl>

					{icon.type === 'upload' && icon.mediaId ?
						<ToolbarGroup>
							<MediaReplaceFlow
								mediaId={icon.mediaId}
								onSelect={handleImageSelect}
								allowedTypes={['image/svg+xml']}
								accept="image/svg+xml"
							/>
							<ToolbarButton
								onClick={() => setAttributes({ icon: DEFAULT_ICON })}
								icon="trash"
								label={__('Remove Icon', 'lead-gen')}
							/>
						</ToolbarGroup>
					: null}

					{icon.type === 'upload' && (
						<Image
							id={icon.mediaId || null}
							size="full"
							onSelect={handleImageSelect}
							allowedTypes={['image/svg+xml']}
							labels={{
								title: 'Select SVG Image',
								instructions: 'Upload or pick an SVG image.',
							}}
						/>
					)}

					{icon.type === 'library' && (
						<IconPicker
							value={{ name: icon.library, iconSet: icon.iconSet }}
							onChange={handleLibraryIconSelect}
						/>
					)}

					<ToggleGroupControl
						label={__('Icon Display', 'lead-gen')}
						value={iconDisplay || 'decorative'}
						isBlock
						__nextHasNoMarginBottom
						__next40pxDefaultSize
						onChange={(val) => setAttributes({ iconDisplay: val })}
					>
						<ToggleGroupControlOption value="decorative" label="Decorative" />
						<ToggleGroupControlOption value="informational" label="Informational" />
					</ToggleGroupControl>
				</PanelBody>

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

			<div
				id={anchor || undefined}
				className="lg-block lg-block__icon"
			>
				<span className="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>
			</div>
		</AnimatedBlockWrapper>
	);
};

export default Edit;
