'use client';

import { useState, useEffect, useMemo } from 'react';
import { useInventoryStore } from '@/store/useInventoryStore';
import shared from '../../styles/shared.module.css';
import styles from '../../styles/Dlcs.module.css';
import {
	PlatformFilter,
	isOnSteam,
	isOnEpic,
	isOnXbox,
	matchesPlatform
} from './types';
import { DLC, isNamedDLC } from '@/lib/utils';
import { fetchDLCs } from '@/lib/db';

const PLATFORM_FILTER_LABELS: Record<PlatformFilter, string> = {
	all: 'All',
	steam: 'Steam',
	epic: 'Epic',
	xbox: 'Xbox'
};

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

	const [allDlcs, setAllDlcs] = useState<DLC[]>([]);
	const [search, setSearch] = useState('');
	const [platformFilter, setPlatformFilter] = useState<PlatformFilter>('all');
	const [statusFilter, setStatusFilter] = useState<
		'all' | 'unlocked' | 'locked'
	>('all');

	useEffect(() => {
		fetchDLCs().then((data: DLC[]) => setAllDlcs(data.filter(isNamedDLC)));
	}, []);

	const filtered = useMemo(() => {
		return allDlcs.filter((dlc) => {
			if (!matchesPlatform(dlc, platformFilter)) return false;
			if (
				search.trim() &&
				!dlc.name!.toLowerCase().includes(search.toLowerCase())
			)
				return false;
			if (statusFilter === 'unlocked' && !store.unlockedDLCs.includes(dlc.id))
				return false;
			if (statusFilter === 'locked' && store.unlockedDLCs.includes(dlc.id))
				return false;
			return true;
		});
	}, [allDlcs, search, platformFilter, statusFilter, store.unlockedDLCs]);

	const handleToggle = (id: string) => store.toggleItem(id, 'dlcs');

	const handleUnlockShown = () => {
		const ids = filtered.map((d) => d.id);
		const merged = Array.from(new Set([...store.unlockedDLCs, ...ids]));
		store.unlockAllInCategory('dlcs', merged);
	};

	const handleLockShown = () => {
		const ids = new Set(filtered.map((d) => d.id));
		const remaining = store.unlockedDLCs.filter((id) => !ids.has(id));
		store.unlockAllInCategory('dlcs', remaining);
	};

	const handleUnlockAll = () => {
		store.unlockAllInCategory(
			'dlcs',
			allDlcs.map((d) => d.id)
		);
	};

	return (
		<div className={shared.container}>
			<header className={shared.header}>
				<div>
					<h1 className={shared.title}>DLCs</h1>
					<p className={shared.subtitle}>
						{store.unlockedDLCs.length} of {allDlcs.length || '-'} dlcs unlocked
					</p>
				</div>
				<div style={{ display: 'flex', gap: '0.75rem' }}>
					<button className={shared.unlockAllBtn} onClick={handleUnlockAll}>
						Unlock All ({allDlcs.length})
					</button>
					<button
						className={shared.clearBtn}
						onClick={() => store.clearCategory('dlcs')}
					>
						Clear All
					</button>
				</div>
			</header>

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

				<div className={shared.roleFilter}>
					{(Object.keys(PLATFORM_FILTER_LABELS) as PlatformFilter[]).map(
						(p) => (
							<button
								key={p}
								className={`${shared.roleBtn} ${platformFilter === p ? shared.roleBtnActive : ''}`}
								onClick={() => setPlatformFilter(p)}
							>
								{PLATFORM_FILTER_LABELS[p]}
							</button>
						)
					)}
				</div>

				<div className={shared.roleFilter}>
					{(['all', 'unlocked', 'locked'] as const).map((s) => (
						<button
							key={s}
							className={`${shared.roleBtn} ${statusFilter === s ? shared.roleBtnActive : ''}`}
							onClick={() => setStatusFilter(s)}
						>
							{s}
						</button>
					))}
				</div>

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

				<button className={shared.unlockAllBtn} onClick={handleUnlockShown}>
					Unlock Shown
				</button>
				<button className={shared.lockAllBtn} onClick={handleLockShown}>
					Lock Shown
				</button>
			</div>

			{filtered.length === 0 ? (
				<div className={shared.empty}>No DLCs match</div>
			) : (
				<div className={styles.grid}>
					{filtered.map((dlc) => {
						const unlocked = store.unlockedDLCs.includes(dlc.id);
						return (
							<div
								key={dlc.id}
								className={`${styles.card} ${unlocked ? styles.cardUnlocked : ''}`}
								onClick={() => handleToggle(dlc.id)}
							>
								<span className={styles.cardName}>{dlc.name}</span>
								<div className={styles.platforms}>
									<span
										className={`${styles.badge} ${isOnSteam(dlc) ? styles.badgeSteam : styles.badgeOff}`}
									>
										ST
									</span>
									<span
										className={`${styles.badge} ${isOnEpic(dlc) ? styles.badgeEpic : styles.badgeOff}`}
									>
										EP
									</span>
									<span
										className={`${styles.badge} ${isOnXbox(dlc) ? styles.badgeXbox : styles.badgeOff}`}
									>
										XB
									</span>
								</div>
							</div>
						);
					})}
				</div>
			)}
		</div>
	);
}
