import { useState, useMemo } from 'react'
import type { Game, NuzlockeRun } 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
  runs?: NuzlockeRun[]
}

export function GameGrid({ games, selectedId, onSelect, runs }: GameGridProps) {
  const [filter, setFilter] = useState<number | null>(null)
  const [regionFilter, setRegionFilter] = useState<string | null>(null)
  const [hideWithActiveRun, setHideWithActiveRun] = useState(false)
  const [hideCompleted, setHideCompleted] = useState(false)

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

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

  const activeRunGameIds = useMemo(() => {
    if (!runs) return new Set<number>()
    return new Set(runs.filter((r) => r.status === 'active').map((r) => r.gameId))
  }, [runs])

  const completedRunGameIds = useMemo(() => {
    if (!runs) return new Set<number>()
    return new Set(runs.filter((r) => r.status === 'completed').map((r) => r.gameId))
  }, [runs])

  const filtered = useMemo(() => {
    let result = games
    if (filter) result = result.filter((g) => g.generation === filter)
    if (regionFilter) result = result.filter((g) => g.region === regionFilter)
    if (hideWithActiveRun) result = result.filter((g) => !activeRunGameIds.has(g.id))
    if (hideCompleted) result = result.filter((g) => !completedRunGameIds.has(g.id))
    return result
  }, [games, filter, regionFilter, hideWithActiveRun, hideCompleted, activeRunGameIds, completedRunGameIds])

  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])

  const pillClass = (active: boolean) =>
    `px-3 py-1.5 text-sm font-medium rounded-full transition-colors ${
      active
        ? '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'
    }`

  return (
    <div className="space-y-6">
      <div className="space-y-3">
        <div className="flex flex-wrap items-center gap-2">
          <span className="text-xs font-medium text-gray-500 dark:text-gray-400 mr-1">Gen:</span>
          <button
            type="button"
            onClick={() => setFilter(null)}
            className={pillClass(filter === null)}
          >
            All
          </button>
          {generations.map((gen) => (
            <button
              key={gen}
              type="button"
              onClick={() => setFilter(gen)}
              className={pillClass(filter === gen)}
            >
              Gen {gen}
            </button>
          ))}
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <span className="text-xs font-medium text-gray-500 dark:text-gray-400 mr-1">Region:</span>
          <button
            type="button"
            onClick={() => setRegionFilter(null)}
            className={pillClass(regionFilter === null)}
          >
            All
          </button>
          {regions.map((region) => (
            <button
              key={region}
              type="button"
              onClick={() => setRegionFilter(region)}
              className={pillClass(regionFilter === region)}
            >
              {region.charAt(0).toUpperCase() + region.slice(1)}
            </button>
          ))}
        </div>

        {runs && (
          <div className="flex flex-wrap items-center gap-4">
            <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
              <input
                type="checkbox"
                checked={hideWithActiveRun}
                onChange={(e) => setHideWithActiveRun(e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
              />
              Hide games with active run
            </label>
            <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
              <input
                type="checkbox"
                checked={hideCompleted}
                onChange={(e) => setHideCompleted(e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
              />
              Hide completed games
            </label>
          </div>
        )}
      </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>
  )
}
