import 'package:flutter/material.dart';

import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/model/hall_of_fame.dart';
import 'package:asciineverdie/src/core/storage/hall_of_fame_storage.dart';
import 'package:asciineverdie/src/features/arena/arena_setup_screen.dart';
import 'package:asciineverdie/src/features/arena/widgets/arena_rank_card.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_panel.dart';

/// 로컬 아레나 메인 화면
///
/// 순위표 표시 및 도전하기 버튼
class ArenaScreen extends StatefulWidget {
  const ArenaScreen({super.key});

  @override
  State<ArenaScreen> createState() => _ArenaScreenState();
}

class _ArenaScreenState extends State<ArenaScreen> {
  final HallOfFameStorage _storage = HallOfFameStorage();
  HallOfFame? _hallOfFame;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadHallOfFame();
  }

  Future<void> _loadHallOfFame() async {
    final hallOfFame = await _storage.load();

    if (mounted) {
      setState(() {
        _hallOfFame = hallOfFame;
        _isLoading = false;
      });
    }
  }

  /// 캐릭터 선택 시 바로 슬롯 선택 화면으로 이동
  void _selectChallenger(HallOfFameEntry challenger) {
    if (_hallOfFame == null || _hallOfFame!.count < 2) return;

    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (context) => ArenaSetupScreen(
          hallOfFame: _hallOfFame!,
          initialChallenger: challenger,
          onBattleComplete: _onBattleComplete,
        ),
      ),
    );
  }

  void _onBattleComplete(HallOfFame updatedHallOfFame) {
    setState(() {
      _hallOfFame = updatedHallOfFame;
    });
  }

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);
    return Scaffold(
      backgroundColor: RetroColors.backgroundOf(context),
      appBar: AppBar(
        title: Text(
          l10n.arenaTitle,
          style: const TextStyle(fontFamily: 'PressStart2P', fontSize: 15),
        ),
        centerTitle: true,
        backgroundColor: RetroColors.panelBgOf(context),
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    final hallOfFame = _hallOfFame;
    if (hallOfFame == null || hallOfFame.count < 2) {
      return _buildEmptyState();
    }

    return Column(
      children: [
        // 순위표 (캐릭터 선택)
        Expanded(child: _buildRankingList(hallOfFame)),
      ],
    );
  }

  Widget _buildEmptyState() {
    final l10n = L10n.of(context);
    return Center(
      child: RetroPanel(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.sports_kabaddi,
              size: 64,
              color: RetroColors.textMutedOf(context),
            ),
            const SizedBox(height: 16),
            Text(
              l10n.arenaEmptyTitle,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 14,
                color: RetroColors.textSecondaryOf(context),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              l10n.arenaEmptyHint,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 12,
                color: RetroColors.textMutedOf(context),
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRankingList(HallOfFame hallOfFame) {
    final rankedEntries = hallOfFame.rankedEntries;

    return Padding(
      padding: const EdgeInsets.all(12),
      child: RetroGoldPanel(
        title: L10n.of(context).arenaSelectFighter,
        padding: const EdgeInsets.all(8),
        child: ListView.builder(
          itemCount: rankedEntries.length,
          itemBuilder: (context, index) {
            final entry = rankedEntries[index];
            final score = HallOfFameArenaX.calculateArenaScore(entry);
            return ArenaRankCard(
              entry: entry,
              rank: index + 1,
              score: score,
              onTap: () => _selectChallenger(entry),
            );
          },
        ),
      ),
    );
  }
}
