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

const DEFAULT_COLOR = '#6366f1' // indigo-500

interface GameCardProps {
  game: Game
  selected: boolean
  onSelect: (game: Game) => void
}

export function GameCard({ game, selected, onSelect }: GameCardProps) {
  const backgroundColor = game.color ?? DEFAULT_COLOR
  const [imgError, setImgError] = useState(false)
  const boxArtSrc = `/boxart/${game.slug}.png`

  return (
    <button
      type="button"
      onClick={() => onSelect(game)}
      className={`relative w-full rounded-lg overflow-hidden transition-all duration-200 hover:scale-105 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 ${
        selected ? 'ring-2 ring-blue-500 scale-105 shadow-lg' : 'shadow'
      }`}
    >
      {!imgError ? (
        <img
          src={boxArtSrc}
          alt={game.name}
          className="w-full h-48 object-cover"
          onError={() => setImgError(true)}
        />
      ) : (
        <div
          className="w-full h-48 flex items-center justify-center"
          style={{ backgroundColor }}
        >
          <span className="text-white text-2xl font-bold text-center px-4 drop-shadow-md">
            {game.name.replace('Pokemon ', '')}
          </span>
        </div>
      )}
      <div className="p-3 bg-white dark:bg-gray-800 text-left">
        <h3 className="font-semibold text-gray-900 dark:text-gray-100">
          {game.name}
        </h3>
        <div className="flex items-center gap-2 mt-1">
          <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
            {game.region.charAt(0).toUpperCase() + game.region.slice(1)}
          </span>
          {game.releaseYear && (
            <span className="text-xs text-gray-500 dark:text-gray-400">
              {game.releaseYear}
            </span>
          )}
        </div>
      </div>
      {selected && (
        <div className="absolute top-2 right-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
          <svg
            className="w-4 h-4 text-white"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={3}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M5 13l4 4L19 7"
            />
          </svg>
        </div>
      )}
    </button>
  )
}
