import { __ } from '@wordpress/i18n';
import {
	InspectorControls,
	MediaUpload,
	MediaUploadCheck,
} from '@wordpress/block-editor';
import {
	PanelBody,
	SelectControl,
	ToggleControl,
	Button,
	TextareaControl,
} from '@wordpress/components';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import AnimationControls from '../components/animations/AnimationControl';
import LinkBlockControl from "../components/LinkBlockControl/LinkBlockControl";
import PlaceholderDimensionControls from '../components/PlaceholderDimension/PlaceholderDimensionControls';
import { useSelect } from '@wordpress/data';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";


const Edit = ({ attributes, setAttributes }) => {
	const {
		mediaId,
		caption,
		showCaption,
		placeholderDimensions,
		imageSize,
		animationEntrance,
		animationDuration,
		animationDelay,
		link,
	} = attributes;

	const width = placeholderDimensions?.width || 600;
	const height = placeholderDimensions?.height || 400;

	const onSelectMedia = (media) => {
		setAttributes({
			mediaId: media.id,
			caption: '',
		});
	};

	const onRemoveMedia = () => {
		setAttributes({
			mediaId: null,
			caption: '',
		});
	};

	const stripHTML = (html) => {
		const temp = document.createElement('div');
		temp.innerHTML = html;
		return temp.textContent || temp.innerText || '';
	};

	const mediaData = useSelect(
		(select) => {
			if (!mediaId) return null;
			const media = select('core').getMedia(mediaId);
			if (!media) return null;

			const sizes = media.media_details?.sizes;
			const selectedSize = sizes?.[imageSize];
			return {
				url: selectedSize?.source_url || media.source_url,
				alt: media.alt_text || '',
				caption: stripHTML(media.caption?.rendered || ''),
				mime_type: media.mime_type || '',
			};
		},
		[mediaId, imageSize]
	);

	const effectiveCaption = caption?.trim() !== '' ? caption : mediaData?.caption?.trim() || '';
	const showFigure = showCaption && effectiveCaption !== '';
	const WrapperTag = showFigure ? 'figure' : 'div';

	const isImage = mediaData?.mime_type?.startsWith('image/');
	const isVideo = mediaData?.mime_type?.startsWith('video/');
	const isAudio = mediaData?.mime_type?.startsWith('audio/');

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			tagName={WrapperTag}
			className={`lg-block lg-block__media ${getVisibilityClasses(attributes)}`}
		>
			<InspectorControls>
				<PanelBody title={__('Media Settings', 'lead-gen')} initialOpen={true}>
					<MediaUploadCheck>
						<MediaUpload
							onSelect={onSelectMedia}
							allowedTypes={['image', 'video', 'audio']}
							value={mediaId}
							render={({ open }) => (
								<Button onClick={open} isPrimary>
									{mediaId ? __('Replace Media', 'lead-gen') : __('Select or Upload Media', 'lead-gen')}
								</Button>
							)}
						/>
						{mediaId && (
							<Button onClick={onRemoveMedia} isDestructive style={{ marginTop: '10px' }}>
								{__('Remove Media', 'lead-gen')}
							</Button>
						)}
						<hr />
					</MediaUploadCheck>

					{isImage && (
						<SelectControl
							label={__('Image Size', 'lead-gen')}
							value={imageSize}
							options={[
								{ label: 'Full', value: 'full' },
								{ label: 'Large', value: 'large' },
								{ label: 'Medium', value: 'medium' },
								{ label: 'Thumbnail', value: 'thumbnail' },
							]}
							onChange={(val) => setAttributes({ imageSize: val })}
						/>
					)}

					<ToggleControl
						label={__('Show Caption', 'lead-gen')}
						checked={showCaption}
						onChange={(val) => setAttributes({ showCaption: val })}
					/>
					{showCaption && (
						<TextareaControl
							label={__('Caption Text', 'lead-gen')}
							value={caption}
							onChange={(val) => setAttributes({ caption: val })}
							help={!caption && mediaData?.caption ? __('Using caption from media by default. This will be overridden when you type.', 'lead-gen') : ''}
						/>
					)}
				</PanelBody>

				<PlaceholderDimensionControls
					attributes={attributes}
					setAttributes={setAttributes}
				/>
				<LinkBlockControl
					link={link}
					setAttributes={setAttributes}
				/>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			{mediaData ? (
				<>
					{isImage && (
						<img
							className="media__image"
							src={mediaData.url}
							alt={mediaData.alt}
						/>
					)}
					{isVideo && (
						<video controls className="media__video" width={width} height={height}>
							<source src={mediaData.url} type={mediaData.mime_type} />
						</video>
					)}
					{isAudio && (
						<audio controls className="media__audio">
							<source src={mediaData.url} type={mediaData.mime_type} />
						</audio>
					)}
				</>
			) : (
				<img
					className="media__image"
					src={`https://placehold.co/${width}x${height}`}
					alt="Placeholder"
				/>
			)}
			{showFigure && (
				<figcaption className="media__caption">{effectiveCaption}</figcaption>
			)}
		</AnimatedBlockWrapper>
	);
};

export default Edit;
