'use client';

import { useState, useEffect, useMemo } from 'react';
import { useInventoryStore } from '@/store/useInventoryStore';
import styles from '../../styles/Characters.module.css';

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

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

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

const isKiller = (idx: number) => idx >= 268435456;

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

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

    useEffect(() => {
        fetch('/data/characters.json')
            .then(r => r.json())
            .then(setCharacters)
            .catch(() => []);
    }, []);

    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 = (idx: number) => {
        store.toggleItem(idx.toString(), 'characters');
    };

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

    const handleLockAll = () => {
        const ids = filtered.map(c => c.idx.toString());
        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={styles.container}>
        <header className={styles.header}>
            <div className={styles.headerLeft}>
                <h1 className={styles.title}>Characters</h1>
                <p className={styles.subtitle}>{unlockedCount} of {characters.length} unlocked</p>
            </div>
        </header>

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

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

            <span className={styles.spacer} />

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

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

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

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