'use client';

import { useState, useMemo } from 'react';
import shared from '../../styles/shared.module.css';
import styles from '../../styles/Items.module.css';
import QuantityCard from '../../components/QuantityCard';
import {
	Item,
	ItemType,
	ITEM_TYPE_LABELS,
	getItemType,
	getItemIconUrl
} from './types';
import { randInRange } from '@/lib/utils';

type Props = {
	items: Item[];
	quantities: Record<string, number>;
	randMin: number;
	randMax: number;
	onSetQty: (id: string, qty: number) => void;
};

export default function ItemGrid({
	items,
	quantities,
	randMin,
	randMax,
	onSetQty
}: Props) {
	const [search, setSearch] = useState('');
	const [typeFilter, setTypeFilter] = useState<ItemType>('all');

	const filtered = useMemo(() => {
		return items.filter((item) => {
			if (typeFilter !== 'all' && getItemType(item.id) !== typeFilter)
				return false;
			if (
				search.trim() &&
				!item.name.toLowerCase().includes(search.toLowerCase())
			)
				return false;
			return true;
		});
	}, [items, typeFilter, search]);

	const handleGive100Visible = () =>
		filtered.forEach((i) => onSetQty(i.id, 100));
	const handleRandVisible = () =>
		filtered.forEach((i) => onSetQty(i.id, randInRange(randMin, randMax)));
	const handleLockVisible = () => filtered.forEach((i) => onSetQty(i.id, 0));

	const activeCount = Object.values(quantities).filter((q) => q > 0).length;

	return (
		<>
			<div className={shared.toolbar}>
				<input
					className={shared.searchInput}
					type='text'
					placeholder='Search items...'
					value={search}
					onChange={(e) => setSearch(e.target.value)}
				/>

				<div className={shared.roleFilter}>
					{(Object.keys(ITEM_TYPE_LABELS) as ItemType[]).map((t) => (
						<button
							key={t}
							className={`${shared.roleBtn} ${typeFilter === t ? shared.roleBtnActive : ''}`}
							onClick={() => setTypeFilter(t)}
						>
							{ITEM_TYPE_LABELS[t]}
						</button>
					))}
				</div>

				<span className={shared.spacer} />
				<span className={shared.resultCount}>
					{filtered.length} shown · {activeCount} active
				</span>

				<button className={shared.unlockAllBtn} onClick={handleGive100Visible}>
					Set all to 100
				</button>
				<button className={styles.randBtn} onClick={handleRandVisible}>
					Randomize
				</button>
				<button className={shared.lockAllBtn} onClick={handleLockVisible}>
					Remove all visible
				</button>
			</div>

			{filtered.length === 0 ? (
				<div className={shared.empty}>No items match</div>
			) : (
				<div className={styles.grid}>
					{filtered.map((item) => (
						<QuantityCard
							key={item.id}
							id={item.id}
							name={item.name}
							iconUrl={getItemIconUrl(item.iconFilePath)}
							qty={quantities[item.id] ?? 0}
							randMin={randMin}
							randMax={randMax}
							onSetQty={onSetQty}
						/>
					))}
				</div>
			)}
		</>
	);
}
