import { useSelector, useDispatch } from 'react-redux'
import iconData from '../public/icons.json'
import { useEffect, useRef, useState } from 'react';

export const IconList = function () {
	const [icons, setIcons] = useState(Object.keys(iconData))
	const query = useSelector(state => state.search.query)
	const showName = useSelector(state => state.display.showName)

	useEffect(() => {
		if (query == '') {
			setIcons(Object.keys(iconData))
			return
		}

		const keywords = query.toLowerCase().split(' ').filter(word => (word))
		let filtered = [];
		for (const filename in iconData) {
			const matched = keywords.filter(keyword => {
				for (const tag of iconData[filename]) {
					if (tag.indexOf(keyword.toLowerCase()) != -1) return true
				}
			})
			
			if (matched.length == keywords.length) filtered.push(filename)
		}
		// console.log(filtered)

		setIcons(filtered)
	}, [query])

	function launchDownload (filename) {
		location.href = `https://sqkhor.com/pixel-icons/${filename.replace('.svg', '')}`
		// window.open(`download.php?icon=${filename}`)
	}

	if (icons.length == 0) {
		return (
			<div className="no-result">
				No icon found for<br />"{query.trim().length > 24 ? query.trim().substring(0,24) + '...' : query.trim()}"
			</div>
		)
	}

	return (
		<ul className={ `icon-list ${ showName ? 'show-name' : ''}` }>
			{ icons.map( (filename, index) => (
				<li key={ index }>
					<a href={`https://sqkhor.com/pixel-icons/${filename.replace('.svg', '')}`}><img className='icon' src={ `./icons/${filename}` } /></a>
					<div className='name'>{ showName ? <a href={`https://sqkhor.com/pixel-icons/${filename.replace('.svg', '')}`}>{filename.replace('.svg', '')}</a> : '' }</div>
				</li>
			) ) }
		</ul>
	)
};
