import { LabelControl } from './label';
import { useState } from '@wordpress/element';
var pagelayer_icons = {};

export const IconControl = (props) => {
	const { prop, value, setAttributes	} = props;
	const { name } = prop['c'];
	
	const [curIconSet, setCurIconSet] = useState(pagelayer_loaded_icons[0]);
	const [showIconsList, setShowIconsList] = useState(false);
	const [searchText, setSearchText] = useState('');
	const [activeTabs, setActiveTabs] = useState({
		fas: true,
		far: false,
		fab: false,
	});
	
	var sel_name = value;
	
	// Handle the icon name 
	if(sel_name){
		var icon_name = sel_name.split(' fa-');
		sel_name = icon_name[1];
	}
	
	const handleIconSetChange = (event) => {
		setCurIconSet(event.target.value);
	};

	const handleTabClick = (tab) => {
		setActiveTabs((prevTabs) => ({
			...prevTabs,
			[tab]: !prevTabs[tab],
		}));
	};

	const handleSearchInputChange = (event) => {
		setSearchText(event.target.value);
	};

	const handleIconClick = (event) => {
		setAttributes({ [name]: event.currentTarget.children[0].getAttribute('class')});
	};

	const handleIconClose = () => {
		setAttributes({ [name] : ''});
	};
	
	const iconHtml = (name, cat) => (
		<span className="pagelayer-elp-icon-span" onClick={handleIconClick}>
			<i className={`${cat} fa-${name}`} icon={name}></i> {name}
		</span>
	);

	var allowed_icons = {};

	// Is there a specific list
	if( 'list' in prop && prop.list.length > 0){
		for(var i in pagelayer_icons){
			
			allowed_icons[i] = {};
			
			for(var j in pagelayer_icons[i]){
				
				allowed_icons[i][j] = {};
				var list_icons = [];
				prop.list.forEach(function(item){
					if(pagelayer_icons[i][j]['icons'].includes(item)){
						list_icons.push(item);
					}
					
				});
				allowed_icons[i][j]['icons'] = list_icons;
				allowed_icons[i][j]['pre'] = j;
			}
		}
	}else{
		allowed_icons = pagelayer_icons;
	}
	
	return (
		<div className="components-base-control pagelayer-base-control">
			<LabelControl {...props}/>
			<div className="pagelayer-elp-icon-div" onClick={() => {setShowIconsList(!showIconsList)}}>
				<div className="pagelayer-elp-icon-preview">
					<i className={value}></i>
					<span className="pagelayer-elp-icon-name">
						{value ? sel_name : 'Choose icon'}
					</span>
				</div>
				<span
					className="pagelayer-elp-icon-open"
					onClick={() => setShowIconsList(!showIconsList)}
				>▼</span>
				<span
					className="pagelayer-elp-icon-close"
					style={{ display: value ? 'block' : 'none' }}
					onClick={handleIconClose}
				>
					<b>&times;&nbsp;</b>
				</span>
			</div>
			{ showIconsList && (
				<div className="pagelayer-elp-icon-selector">
					{pagelayer_loaded_icons.length > 1 && (
						<select
							className="pagelayer-elp-icon-sets"
							onChange={handleIconSetChange}
							value={curIconSet}
						>
							{pagelayer_loaded_icons.map((item) => (
								<option key={item} value={item}>
									{item}
								</option>
							))}
						</select>
					)}
					<span className="pagelayer-elp-icon-type">
						<p
							onClick={() => handleTabClick('fas')}
							className={activeTabs.fas ? 'active' : ''}
						>
							{'Solid'}
						</p>
						<p
							onClick={() => handleTabClick('far')}
							className={activeTabs.far ? 'active' : ''}
						>
							{'Regular'}
						</p>
						<p
							onClick={() => handleTabClick('fab')}
							className={activeTabs.fab ? 'active' : ''}
						>
							{'Brand'}
						</p>
					</span>
					<input
						type="text"
						className="pagelayer-elp-search-icon"
						name="search-icon"
						placeholder={'search'}
						value={searchText}
						onChange={handleSearchInputChange}
					/>
					<div className="pagelayer-elp-icon-list">
						{Object.keys(allowed_icons[curIconSet]).map((y) => {
							
							if(!(y in activeTabs) || pagelayer_empty(activeTabs[y])){
								return;
							}
							
							return allowed_icons[curIconSet][y]['icons']
							.filter((item) => item.includes(searchText.toLowerCase()) || searchText.length < 1)
							.map((z) => iconHtml(z, y));
						})}
					</div>
				</div>
			)}
		</div>
	);
}

// Function to fetch and store data
function pagelayer_get_stored_data(url, version){
	const name = 'pagelayer_' + url;
	let data = {};
	let force = false;

	// Try to parse the data
	try {
		data = JSON.parse(localStorage.getItem(name));

		if (data['version'] !== version) {
			force = true;
		}
	} catch (e) {
		force = true;
	}

	// Force download
	if (force) {
		jQuery.ajax({
			url: url,
			type: 'GET',
			dataType: 'text',
			success: function (newData) {
			data = {
				version: version,
				val: newData,
			};
				localStorage.setItem(name, JSON.stringify(data));
			},
		});
	}

	return data['val'];
}

// Load Fonts
wp.domReady(function () {
	
	pagelayer_loaded_icons.forEach((item) => {
		jQuery.when( pagelayer_get_stored_data(pagelayer_url + '/fonts/' + item + '.json', pagelayer_ver))
		.then(() => {
			pagelayer_icons[item] = JSON.parse(pagelayer_get_stored_data( pagelayer_url + '/fonts/' + item + '.json', pagelayer_ver) );
		});
	});
});