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

function CharacterSelection() {
  const { characters, account, selectCharacter, deleteCharacter } = useAuth()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [characterToDelete, setCharacterToDelete] = useState<number | null>(null)
  const navigate = useNavigate()
  const { t } = useTranslation()

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

    try {
      await selectCharacter(characterId)
      navigate('/game')
    } catch (err: any) {
      setError(err.response?.data?.detail || t('common.error'))
    } finally {
      setLoading(false)
    }
  }

  const confirmDelete = (characterId: number) => {
    setCharacterToDelete(characterId)
    setShowDeleteModal(true)
  }

  const handleDeleteCharacter = async () => {
    if (!characterToDelete) return

    setLoading(true)
    setError('')

    try {
      await deleteCharacter(characterToDelete)
      setShowDeleteModal(false)
      setCharacterToDelete(null)
    } catch (err: any) {
      setError(err.response?.data?.detail || t('common.error'))
    } finally {
      setLoading(false)
    }
  }

  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="char-selection-page">
      <div className="char-selection-container">
        <div className="char-selection-header game-panel">
          <h1 className="title-main">{t('characters.title')}</h1>
          <p className="subtitle-sub">Echoes of the Ash</p>
        </div>

        {error && <div className="error-banner game-panel">{error}</div>}

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

          {canCreateCharacter && (
            <div className="char-card-ui create-card game-panel" onClick={handleCreateCharacter}>
              <div className="create-icon-wrapper">
                <span className="create-icon">+</span>
              </div>
              <h3>{t('characters.create.title', 'Create New')}</h3>
              <p className="create-subtitle">
                {characters.length} / {maxCharacters} {t('characters.create.slots', 'slots used')}
              </p>
            </div>
          )}
        </div>

        {!canCreateCharacter && !isPremium && (
          <div className="premium-banner-ui game-panel">
            <h3>{t('characters.premium.title', 'Character Limit Reached')}</h3>
            <p>{t('characters.premium.description', 'Upgrade to Premium to create up to 10 characters!')}</p>
            <GameButton variant="primary" onClick={() => { }}>{t('characters.premium.upgrade', 'Upgrade to Premium')}</GameButton>
          </div>
        )}

        {characters.length === 0 && (
          <div className="no-chars-box game-panel">
            <p>{t('characters.noCharacters')}</p>
            <p>{t('characters.createFirst')}</p>
          </div>
        )}

        {showDeleteModal && (
          <GameModal
            title={t('characters.deleteModal.title', 'Delete Character')}
            onClose={() => setShowDeleteModal(false)}
            footer={
              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end', width: '100%' }}>
                <GameButton variant="secondary" onClick={() => setShowDeleteModal(false)}>
                  {t('common.cancel')}
                </GameButton>
                <GameButton variant="danger" onClick={handleDeleteCharacter}>
                  {t('common.confirm')}
                </GameButton>
              </div>
            }
          >
            <p>{t('characters.deleteModal.confirm', 'Are you sure you want to delete this character? This action cannot be undone.')}</p>
          </GameModal>
        )}
      </div>
    </div>
  )
}

function CharacterCard({
  character,
  onSelect,
  onDelete,
  loading
}: {
  character: Character
  onSelect: () => void
  onDelete: () => void
  loading: boolean
}) {
  const { t } = useTranslation()

  const formatDate = (dateString: string) => {
    try {
      if (!dateString) return 'Never'
      // Timestamp from API is float seconds, convert to ms
      const timestamp = typeof dateString === 'number' ? dateString * 1000 : dateString
      const date = new Date(timestamp)
      // Check if date is valid (1970 usually means 0 timestamp/invalid in some contexts, but let's just check validity)
      if (isNaN(date.getTime()) || date.getFullYear() === 1970) return 'Never'
      return date.toLocaleDateString()
    } catch (e) {
      return 'Invalid Date'
    }
  }

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

      <div className="char-info-box">
        <div className="char-meta-header">
          <h3>{character.name}</h3>
          <span className="level-badge" style={{ clipPath: 'var(--game-clip-path-sm)', borderRadius: 0 }}>
            {t('stats.level')} {character.level}
          </span>
        </div>

        <div className="char-stats-preview">
          <div className="stat-preview">
            <span className="label text-red-400">{t('stats.hp')}</span>
            <span className="value">{character.hp}/{character.max_hp}</span>
          </div>
          <div className="stat-preview">
            <span className="label text-yellow-400">{t('stats.stamina')}</span>
            <span className="value">{character.stamina}/{character.max_stamina}</span>
          </div>
          <div className="stat-preview">
            <span className="label text-blue-400">{t('stats.weight')}</span>
            <span className="value">{character.weight}/{character.max_weight}</span>
          </div>
          <div className="stat-preview">
            <span className="label text-purple-400">{t('stats.volume')}</span>
            <span className="value">{character.volume}/{character.max_volume}</span>
          </div>
        </div>

        <div className="char-attr-grid">
          <GameTooltip content={t('stats.strength')}>
            <div className="attr-item">💪 {character.strength}</div>
          </GameTooltip>
          <GameTooltip content={t('stats.agility')}>
            <div className="attr-item">⚡ {character.agility}</div>
          </GameTooltip>
          <GameTooltip content={t('stats.endurance')}>
            <div className="attr-item">🛡️ {character.endurance}</div>
          </GameTooltip>
          <GameTooltip content={t('stats.intellect')}>
            <div className="attr-item">🧠 {character.intellect}</div>
          </GameTooltip>
        </div>

        <p className="last-played">
          {t('characters.lastActive')}: {formatDate(character.last_played_at)}
        </p>
      </div>

      <div className="char-card-actions">
        <GameButton
          variant="primary"
          onClick={onSelect}
          disabled={loading}
          className="play-btn"
        >
          {loading ? t('common.loading') : t('characters.play')}
        </GameButton>
        <GameButton
          variant="danger"
          onClick={onDelete}
          disabled={loading}
        >
          {t('characters.delete')}
        </GameButton>
      </div>
    </div>
  )
}

export default CharacterSelection
