import { LabelControl } from './label';
import { __ } from '@wordpress/i18n';
import { MediaUpload } from '@wordpress/block-editor';
import { useState, useRef, useEffect } from '@wordpress/element';

export const MultiImageControl = (props) => {
	
	const { prop, label, value, setAttributes, attributes, allow = ['image'] } = props;
	const { name } = prop['c'];
	const tmpAtts = attributes?.tmpAtts ?  attributes.tmpAtts : {};
   
	const [imageIds, setImageIds] = useState([]);
	const [imageUrls, setImageUrls] = useState({});
   
	const onSelectImage = (images) => {
		
		var ids = [];
		var urls = {};
		var img_urls = {};
		var titles = {};
		var links = {};
		var captions = {};
		
		for(var i in images){
			
			const { id, url, title, link, caption, sizes} = images[i];
			var _id = 'i'+id;
			
			ids.push(id);
			urls[_id] = url;
			
			//get title
			titles[_id] = title;
			links[_id] = link;
			captions[_id] = caption;
			
			// Create a URL
			img_urls[_id] = {}
			
			for(var x in sizes){
				img_urls[_id][x] = sizes[x].url;
			}
		}
			
		setImageUrls(urls);
		setImageIds(ids);
		
		const tmp = {
			...tmpAtts,
			[name+'-urls']: urls,
			[name+'-all-urls']: img_urls,
			[name+'-all-titles']: titles,
			[name+'-all-links']: links,
			[name+'-all-captions']: captions,
		};
		
		setAttributes({
			[name]: ids,
			tmpAtts: tmp
		});
	}

	useEffect(() => {
		
		var ids = [];
		
		// Any IDs ?
		if(!pagelayer_empty(prop.c['val'])){
			ids = prop.c['val']
			if(pagelayer_is_string(ids)){
				ids = prop.c['val'].split(',');
			}
			//console.log(ids);
			
			setImageIds(ids);
		}
				
		// Query the media library for media items with the specified post IDs.
		wp.media.query({ post__in: ids }).more().then(() => {
			
			var urls = {};
			for(var x in ids){
				var fetch_url = wp.media.attachment(ids[x]).get('url');
				urls['i'+x] = fetch_url;
			};
			
			setImageUrls(urls);
		});
	}, []);

	const renderMediaUploader = (open) => {
		
		return (
			<div className="pagelayer-elp-multi_image-div">
				<center>
					<button 
						className="pagelayer-elp-button"
						onClick={() => open() }
					>
					{ __('Add Images') }
					</button>
				</center>
				<div className="pagelayer-elp-multi_image-thumbs" onClick={ () => open() } >
					{ imageUrls && Object.keys(imageUrls).map((imageName) => (
						<div 
							className="pagelayer-elp-multi_image-thumb"
							style={{
								backgroundImage: `url(${imageUrls[imageName]})`
							}}
						></div>
					))}
				</div>
			</div>
		);
	}
	return (
		<div className="components-base-control pagelayer-base-control">
			<LabelControl {...props} />
			<MediaUpload
				title="Select Image"
				onSelect={onSelectImage}
				allowedTypes={allow}
				value={imageIds}
				multiple={true}
				gallery={true}
				addToGallery={true}
				autoOpen={true}
				render={({ open }) => renderMediaUploader(open)}
			/>
		</div>
	);
}