'use client';

import { useState, useEffect, useMemo } from 'react';
import { useInventoryStore } from '@/store/useInventoryStore';

import { isKiller } from '../../lib/utils';
import { DB_BASE_URL, fetchCharacters } from '../../lib/db';

import shared from '../../styles/shared.module.css';
import styles from '../../styles/Characters.module.css';

type Character = {
	idx: number;
	codeName: string;
	name: string;
	iconFilePath: string;
};

const getIconUrl = (iconFilePath: string) => {
	const fileName = iconFilePath.split('/').pop()?.split('.')[0];
	return `${DB_BASE_URL}/icons/character-icons/${fileName}.png`;
};

type RoleFilter = 'all' | 'survivors' | 'killers';

export default function CharactersPage() {
	const store = useInventoryStore();

	const [characters, setCharacters] = useState<Character[]>([]);
	const [search, setSearch] = useState('');
	const [role, setRole] = useState<RoleFilter>('all');

	useEffect(() => {
		fetchCharacters().then(setCharacters);
	}, []);

	const filtered = useMemo(() => {
		return characters.filter((c) => {
			if (role === 'survivors' && isKiller(c.idx)) return false;
			if (role === 'killers' && !isKiller(c.idx)) return false;
			if (search.trim() && !c.name.toLowerCase().includes(search.toLowerCase()))
				return false;
			return true;
		});
	}, [characters, search, role]);

	const handleToggle = (codeName: string) => {
		store.toggleItem(codeName, 'characters');
	};

	const handleUnlockAll = () => {
		const ids = filtered.map((c) => c.codeName);
		const outside = store.unlockedCharacters.filter(
			(id) => !filtered.some((c) => c.codeName === id)
		);
		store.unlockAllInCategory('characters', [...outside, ...ids]);
	};

	const handleLockAll = () => {
		const ids = filtered.map((c) => c.codeName);
		const newUnlocked = store.unlockedCharacters.filter(
			(id) => !ids.includes(id)
		);
		store.unlockAllInCategory('characters', newUnlocked);
	};

	const handleClear = () => {
		store.clearCategory('characters');
	};
	const unlockedCount = store.unlockedCharacters.length;

	return (
		<div className={shared.container}>
			<header className={shared.header}>
				<div className={shared.headerLeft}>
					<h1 className={shared.title}>Characters</h1>
					<p className={shared.subtitle}>
						{unlockedCount} of {characters.length} unlocked
					</p>
				</div>
			</header>

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

				<div className={shared.roleFilter}>
					{(['all', 'survivors', 'killers'] as RoleFilter[]).map((r) => (
						<button
							key={r}
							className={`${shared.roleBtn} ${role === r ? shared.roleBtnActive : ''}`}
							onClick={() => setRole(r)}
						>
							{r}
						</button>
					))}
				</div>

				<span className={shared.spacer} />

				<span className={shared.resultCount}>{filtered.length} shown</span>

				<button className={shared.unlockAllBtn} onClick={handleUnlockAll}>
					Unlock shown
				</button>

				<button className={shared.lockAllBtn} onClick={handleLockAll}>
					Lock shown
				</button>
				<button className={shared.clearBtn} onClick={handleClear}>
					Clear all
				</button>
			</div>

			{filtered.length === 0 ? (
				<div className={shared.empty}>No characters match</div>
			) : (
				<div className={styles.grid}>
					{filtered.map((char) => {
						const unlocked = store.unlockedCharacters.includes(
							char.codeName
						);
						const killer = isKiller(char.idx);
						return (
							<div
								key={char.codeName}
								className={`${shared.card} ${unlocked ? shared.cardUnlocked : ''}`}
								onClick={() => handleToggle(char.codeName)}
							>
								<img
									className={shared.cardIcon}
									src={getIconUrl(char.iconFilePath)}
									alt={char.name}
									loading='lazy'
								/>
								<span className={shared.cardName}>{char.name}</span>
								<span
									className={`${shared.rolePip} ${killer ? shared.rolePipKiller : ''}`}
								>
									{killer ? 'Killer' : 'Survivor'}
								</span>
							</div>
						);
					})}
				</div>
			)}
		</div>
	);
}
