import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../hooks/useAuth'
import { Character } from '../services/api'
import './CharacterSelection.css'
import { GameTooltip } from './common/GameTooltip'

function CharacterSelection() {
  const { characters, account, selectCharacter, deleteCharacter, logout } = useAuth()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const navigate = useNavigate()

  const handleSelectCharacter = async (characterId: number) => {
    setLoading(true)
    setError('')

    try {
      await selectCharacter(characterId)
      navigate('/game')
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to select character')
    } finally {
      setLoading(false)
    }
  }

  const handleDeleteCharacter = async (characterId: number) => {
    if (!window.confirm('Are you sure you want to delete this character? This action cannot be undone.')) {
      return
    }

    setDeletingId(characterId)
    setError('')

    try {
      await deleteCharacter(characterId)
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to delete character')
    } finally {
      setDeletingId(null)
    }
  }

  const handleCreateCharacter = () => {
    navigate('/create-character')
  }

  const isPremium = account?.premium_expires_at !== null
  const maxCharacters = isPremium ? 10 : 1
  const canCreateCharacter = characters.length < maxCharacters

  return (
    <div className="character-selection-container">
      <div className="character-selection-header">
        <h1>Select Your Character</h1>
        <p className="subtitle">Echoes of the Ash</p>
        <button className="button-secondary logout-button" onClick={logout}>
          Logout
        </button>
      </div>

      {error && <div className="error">{error}</div>}

      <div className="characters-grid">
        {characters.map((character) => (
          <CharacterCard
            key={character.id}
            character={character}
            onSelect={() => handleSelectCharacter(character.id)}
            onDelete={() => handleDeleteCharacter(character.id)}
            loading={loading || deletingId === character.id}
          />
        ))}

        {canCreateCharacter && (
          <div className="character-card create-character-card" onClick={handleCreateCharacter}>
            <div className="create-character-icon">+</div>
            <h3>Create New Character</h3>
            <p className="create-character-subtitle">
              {characters.length} / {maxCharacters} slots used
            </p>
          </div>
        )}
      </div>

      {!canCreateCharacter && !isPremium && (
        <div className="premium-banner">
          <h3>Character Limit Reached</h3>
          <p>Upgrade to Premium to create up to 10 characters!</p>
          <button className="button-primary">Upgrade to Premium - $4.99</button>
        </div>
      )}

      {characters.length === 0 && (
        <div className="no-characters">
          <p>You don't have any characters yet.</p>
          <p>Click the "Create New Character" button to get started!</p>
        </div>
      )}
    </div>
  )
}

function CharacterCard({
  character,
  onSelect,
  onDelete,
  loading
}: {
  character: Character
  onSelect: () => void
  onDelete: () => void
  loading: boolean
}) {
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString()
  }

  return (
    <div className="character-card">
      <div className="character-avatar">
        {character.avatar_data?.image ? (
          <img src={character.avatar_data.image} alt={character.name} />
        ) : (
          <div className="avatar-placeholder">
            {character.name.substring(0, 2).toUpperCase()}
          </div>
        )}
      </div>

      <div className="character-info">
        <h3>{character.name}</h3>
        <div className="character-stats">
          <span className="stat">Level {character.level}</span>
          <span className="stat">HP: {character.hp}/{character.max_hp}</span>
        </div>


        <div className="character-attributes">
          <GameTooltip content="Strength">
            <span className="stat-icon">💪 {character.strength}</span>
          </GameTooltip>
          <GameTooltip content="Agility">
            <span>⚡ {character.agility}</span>
          </GameTooltip>
          <GameTooltip content="Endurance">
            <span>🛡️ {character.endurance}</span>
          </GameTooltip>
          <GameTooltip content="Intellect">
            <span>🧠 {character.intellect}</span>
          </GameTooltip>
        </div>
        <p className="character-meta">
          Last played: {formatDate(character.last_played_at)}
        </p>
      </div>

      <div className="character-actions">
        <button
          className="button-primary"
          onClick={onSelect}
          disabled={loading}
        >
          {loading ? 'Loading...' : 'Play'}
        </button>
        <button
          className="button-danger"
          onClick={onDelete}
          disabled={loading}
        >
          Delete
        </button>
      </div>
    </div>
  )
}

export default CharacterSelection
