import {__} from '@wordpress/i18n';
import {MediaUpload} from '@wordpress/block-editor';
import classnames from 'classnames';
import Tooltip from 'react-tooltip-lite';

const SLIDER_ALLOWED_MEDIA_TYPES = ['image', 'video'];

export function UploadMedia(props) {
	const {slide, slides, index} = props;

	const tooltip = slide.url ? __('Replace Media', 'flo') : __('Add Image/Video', 'flo');

	const uploadImage = (
		<MediaUpload
			onSelect={(selectedMediaFiles) => {
				let slidesClone = slides.slice(); //use .slice to produce a new array reference

				// iterate though all the selected media.
				// the first media will be inserted in the selected slide,
				// while the rest will create new Slides
				selectedMediaFiles.map((media, currIndex) => {
					let selectedMediaProps = {
						url: media.url,
						alt: media.alt,
						caption: media.caption,
						id: media.id,
						type: media.type,
						imgHeight: media.height,
						imgWidth: media.width,
					};

					if (currIndex === 0) {
						let newSlide = Object.assign(slide, selectedMediaProps);
						slidesClone[index] = newSlide;
					} else {
						// create a clone from prev slide and change just the media Props
						// we are doing that to not write code for a new empty slide object )
						let prevSlideClone = Object.assign(
								{},
								slidesClone[slidesClone.length - 1]
							),
							prevSlideModiffied = Object.assign(
								prevSlideClone,
								selectedMediaProps
							);

						slidesClone.push(prevSlideModiffied);
					}
				});

				// update the slides Attribute - to make sure all the new added slides are available
				props.setAttributes({slides: slidesClone});
			}}
			allowedTypes={SLIDER_ALLOWED_MEDIA_TYPES}
			multiple={true}
			value={slide.id}
			render={({open}) => (
				<Tooltip content={tooltip} className={classnames('flo-slider-tooltip',slide.url ? 'flo-slider-tooltip--replace' : 'flo-slider-tooltip--add')}>
					<div
						className={classnames(
							slide.url
								? 'gbp-icon-sync replace-media-icon'
								: 'gbp-icon-image-upload upload-media-icon'
						)}
						isSecondary
						onClick={open}
					>
					</div>
				</Tooltip>
			)}
		/>
	);

	return uploadImage;
}
