import { useSelector, useDispatch } from 'react-redux'
import iconData from './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
				}
			})
			// const matched = iconData[filename].filter(tag => {
			// 	for (const keyword of keywords) {
			// 		if (tag.indexOf(keyword.toLowerCase()) != -1) return true
			// 	}
			// 	return false
			// })
			
			if (matched.length == keywords.length) filtered.push(filename)
		}
		console.log(filtered)

		setIcons(filtered)
	}, [query])

	function launchDownload (filename) {
		window.open(`download.php?icon=${filename}`)
	}

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