import 'package:flutter/material.dart';

import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/engine/arena_service.dart';
import 'package:asciineverdie/src/core/engine/item_service.dart';
import 'package:asciineverdie/src/core/model/arena_match.dart';
import 'package:asciineverdie/src/core/model/equipment_item.dart';
import 'package:asciineverdie/src/core/model/equipment_slot.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_battle_screen.dart';
import 'package:asciineverdie/src/features/arena/widgets/arena_equipment_compare_list.dart';
import 'package:asciineverdie/src/features/arena/widgets/arena_idle_preview.dart';
import 'package:asciineverdie/src/features/arena/widgets/arena_rank_card.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 아레나 설정 화면
///
/// 캐릭터 선택 및 슬롯 선택
class ArenaSetupScreen extends StatefulWidget {
  const ArenaSetupScreen({
    super.key,
    required this.hallOfFame,
    required this.onBattleComplete,
    this.initialChallenger,
  });

  /// 명예의 전당
  final HallOfFame hallOfFame;

  /// 전투 완료 콜백 (업데이트된 명예의 전당 전달)
  final void Function(HallOfFame) onBattleComplete;

  /// 초기 도전자 (메인 화면에서 선택한 경우)
  final HallOfFameEntry? initialChallenger;

  @override
  State<ArenaSetupScreen> createState() => _ArenaSetupScreenState();
}

class _ArenaSetupScreenState extends State<ArenaSetupScreen> {
  final ArenaService _arenaService = ArenaService();
  final HallOfFameStorage _storage = HallOfFameStorage();

  /// 현재 단계 (0: 캐릭터 선택, 1: 슬롯 선택)
  int _step = 0;

  /// 선택된 도전자
  HallOfFameEntry? _challenger;

  /// 자동 결정된 상대
  HallOfFameEntry? _opponent;

  /// 선택된 베팅 슬롯 (도전자가 상대에게서 뺏을 슬롯)
  EquipmentSlot? _selectedSlot;

  /// 상대가 선택한 베팅 슬롯 (패배 시 뺏길 슬롯)
  EquipmentSlot? _opponentBettingSlot;

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

    // 초기 도전자가 있으면 바로 슬롯 선택 단계로 이동
    if (widget.initialChallenger != null) {
      _selectChallenger(widget.initialChallenger!);
    }
  }

  void _selectChallenger(HallOfFameEntry entry) {
    final opponent = _arenaService.findOpponent(widget.hallOfFame, entry.id);

    // AI가 도전자에게서 약탈할 슬롯 미리 계산
    final opponentSlot = _arenaService.selectOpponentBettingSlot(entry);

    setState(() {
      _challenger = entry;
      _opponent = opponent;
      _opponentBettingSlot = opponentSlot;
      _step = 1;
    });
  }

  void _startBattle() {
    if (_challenger == null ||
        _opponent == null ||
        _selectedSlot == null ||
        _opponentBettingSlot == null) {
      return;
    }

    final match = ArenaMatch(
      challenger: _challenger!,
      opponent: _opponent!,
      challengerBettingSlot: _selectedSlot!,
      opponentBettingSlot: _opponentBettingSlot!,
    );

    final navigator = Navigator.of(context);

    navigator.push(
      MaterialPageRoute<void>(
        builder: (ctx) => ArenaBattleScreen(
          match: match,
          onBattleComplete: (result) async {
            // 결과 저장
            var updatedHallOfFame = widget.hallOfFame
                .updateEntry(result.updatedChallenger)
                .updateEntry(result.updatedOpponent);

            await _storage.save(updatedHallOfFame);

            widget.onBattleComplete(updatedHallOfFame);

            // 아레나 화면으로 돌아가기
            if (mounted) {
              navigator.popUntil((route) => route.isFirst);
            }
          },
        ),
      ),
    );
  }

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

  Widget _buildCharacterSelection() {
    final rankedEntries = widget.hallOfFame.rankedEntries;

    return Column(
      children: [
        // 헤더
        Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            L10n.of(context).arenaSelectFighter,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: RetroColors.goldOf(context),
            ),
          ),
        ),
        // 캐릭터 목록
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            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),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildSlotSelection() {
    final recommendedSlot = _calculateRecommendedSlot();

    return Column(
      children: [
        // ASCII 캐릭터 미리보기 (좌: 도전자, 우: 상대 반전)
        ArenaIdlePreview(
          challengerRaceId: _challenger?.race,
          opponentRaceId: _opponent?.race,
        ),
        // 상단 캐릭터 정보 (좌우 대칭)
        _buildCharacterHeaders(),
        // 장비 비교 리스트 (양방향 베팅 표시 포함)
        Expanded(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: ArenaEquipmentCompareList(
              myEquipment: _challenger?.finalEquipment,
              enemyEquipment: _opponent?.finalEquipment,
              selectedSlot: _selectedSlot,
              recommendedSlot: recommendedSlot,
              opponentBettingSlot: _opponentBettingSlot,
              onSlotSelected: (slot) {
                setState(() => _selectedSlot = slot);
              },
            ),
          ),
        ),
        // 하단 버튼
        _buildStartButton(),
      ],
    );
  }

  /// 추천 슬롯 계산 (점수 이득이 가장 큰 슬롯, 무기 제외)
  EquipmentSlot? _calculateRecommendedSlot() {
    if (_challenger == null || _opponent == null) return null;

    EquipmentSlot? bestSlot;
    int maxGain = 0;

    // 베팅 가능한 슬롯만 검사 (무기 제외)
    final bettableSlots = _arenaService.getBettableSlots();
    for (final slot in bettableSlots) {
      final myItem = _findItem(slot, _challenger!.finalEquipment);
      final enemyItem = _findItem(slot, _opponent!.finalEquipment);

      final myScore = myItem != null
          ? ItemService.calculateEquipmentScore(myItem)
          : 0;
      final enemyScore = enemyItem != null
          ? ItemService.calculateEquipmentScore(enemyItem)
          : 0;
      final gain = enemyScore - myScore;

      if (gain > maxGain) {
        maxGain = gain;
        bestSlot = slot;
      }
    }

    return bestSlot;
  }

  /// 장비 찾기 헬퍼
  EquipmentItem? _findItem(EquipmentSlot slot, List<EquipmentItem>? items) {
    if (items == null) return null;
    for (final item in items) {
      if (item.slot == slot) return item;
    }
    return null;
  }

  /// 상단 캐릭터 정보 헤더 (좌우 대칭)
  Widget _buildCharacterHeaders() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 내 캐릭터
          Expanded(child: _buildChallengerInfo()),
          const SizedBox(width: 12),
          // 상대 캐릭터
          Expanded(child: _buildOpponentInfo()),
        ],
      ),
    );
  }

  /// 내 캐릭터 정보 카드
  Widget _buildChallengerInfo() {
    if (_challenger == null) return const SizedBox.shrink();

    final score = HallOfFameArenaX.calculateArenaScore(_challenger!);
    final rank = widget.hallOfFame.getRank(_challenger!.id);

    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.blue.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue, width: 2),
      ),
      child: Row(
        children: [
          // 순위 배지
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: Colors.blue.withValues(alpha: 0.2),
              shape: BoxShape.circle,
              border: Border.all(color: Colors.blue, width: 2),
            ),
            child: Center(
              child: Text(
                '$rank',
                style: const TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 14,
                  color: Colors.blue,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const SizedBox(width: 8),
          // 정보
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _challenger!.characterName,
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 11,
                    color: RetroColors.textPrimaryOf(context),
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Text(
                  'Lv.${_challenger!.level} • $score pt',
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 11,
                    color: RetroColors.textSecondaryOf(context),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 시작 버튼
  Widget _buildStartButton() {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: SizedBox(
        height: 48,
        child: ElevatedButton(
          onPressed: _selectedSlot != null ? _startBattle : null,
          style: ElevatedButton.styleFrom(
            backgroundColor: RetroColors.goldOf(context),
            foregroundColor: RetroColors.backgroundOf(context),
            disabledBackgroundColor: RetroColors.borderOf(
              context,
            ).withValues(alpha: 0.5),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.sports_kabaddi,
                color: _selectedSlot != null
                    ? RetroColors.backgroundOf(context)
                    : RetroColors.textMutedOf(context),
              ),
              const SizedBox(width: 8),
              Text(
                L10n.of(context).arenaStartBattle,
                style: TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 14,
                  color: _selectedSlot != null
                      ? RetroColors.backgroundOf(context)
                      : RetroColors.textMutedOf(context),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 상대 캐릭터 정보 카드 (대칭 스타일)
  Widget _buildOpponentInfo() {
    if (_opponent == null) return const SizedBox.shrink();

    final score = HallOfFameArenaX.calculateArenaScore(_opponent!);
    final rank = widget.hallOfFame.getRank(_opponent!.id);

    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.red.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.red, width: 2),
      ),
      child: Row(
        children: [
          // 순위 배지
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: Colors.red.withValues(alpha: 0.2),
              shape: BoxShape.circle,
              border: Border.all(color: Colors.red, width: 2),
            ),
            child: Center(
              child: Text(
                '$rank',
                style: const TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 14,
                  color: Colors.red,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const SizedBox(width: 8),
          // 정보
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _opponent!.characterName,
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 11,
                    color: RetroColors.textPrimaryOf(context),
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Text(
                  'Lv.${_opponent!.level} • $score pt',
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 11,
                    color: RetroColors.textSecondaryOf(context),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
