import { useState, useMemo } from 'react'
import type { Game } from '../types'
import { GameCard } from './GameCard'

const GENERATION_LABELS: Record<number, string> = {
  1: 'Generation I',
  2: 'Generation II',
  3: 'Generation III',
  4: 'Generation IV',
  5: 'Generation V',
  6: 'Generation VI',
  7: 'Generation VII',
  8: 'Generation VIII',
  9: 'Generation IX',
}

interface GameGridProps {
  games: Game[]
  selectedId: number | null
  onSelect: (game: Game) => void
}

export function GameGrid({ games, selectedId, onSelect }: GameGridProps) {
  const [filter, setFilter] = useState<number | null>(null)

  const generations = useMemo(
    () => [...new Set(games.map((g) => g.generation))].sort(),
    [games],
  )

  const filtered = filter
    ? games.filter((g) => g.generation === filter)
    : games

  const grouped = useMemo(() => {
    const groups: Record<number, Game[]> = {}
    for (const game of filtered) {
      ;(groups[game.generation] ??= []).push(game)
    }
    return Object.entries(groups)
      .map(([gen, games]) => ({ generation: Number(gen), games }))
      .sort((a, b) => a.generation - b.generation)
  }, [filtered])

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2">
        <button
          type="button"
          onClick={() => setFilter(null)}
          className={`px-3 py-1.5 text-sm font-medium rounded-full transition-colors ${
            filter === null
              ? 'bg-blue-600 text-white'
              : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
          }`}
        >
          All
        </button>
        {generations.map((gen) => (
          <button
            key={gen}
            type="button"
            onClick={() => setFilter(gen)}
            className={`px-3 py-1.5 text-sm font-medium rounded-full transition-colors ${
              filter === gen
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            Gen {gen}
          </button>
        ))}
      </div>

      {grouped.map(({ generation, games }) => (
        <div key={generation}>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-3">
            {GENERATION_LABELS[generation] ?? `Generation ${generation}`}
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {games.map((game) => (
              <GameCard
                key={game.id}
                game={game}
                selected={game.id === selectedId}
                onSelect={onSelect}
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  )
}
