import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
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/hall_of_fame/hall_of_fame_entry_card.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_dialog.dart';

// 다른 파일에서 사용할 수 있도록 재export
export 'package:asciineverdie/src/features/hall_of_fame/game_clear_dialog.dart';
export 'package:asciineverdie/src/features/hall_of_fame/hall_of_fame_entry_card.dart';
export 'package:asciineverdie/src/features/hall_of_fame/hero_detail_dialog.dart';

/// 명예의 전당 화면 (Phase 10: Hall of Fame Screen)
class HallOfFameScreen extends StatefulWidget {
  const HallOfFameScreen({super.key});

  @override
  State<HallOfFameScreen> createState() => _HallOfFameScreenState();
}

class _HallOfFameScreenState extends State<HallOfFameScreen> {
  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;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: RetroColors.backgroundOf(context),
      appBar: AppBar(
        title: Text(
          l10n.uiHallOfFame.toUpperCase(),
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: RetroColors.goldOf(context),
          ),
        ),
        centerTitle: true,
        backgroundColor: RetroColors.panelBgOf(context),
        iconTheme: IconThemeData(color: RetroColors.goldOf(context)),
      ),
      body: SafeArea(
        top: false,
        child: _isLoading
            ? Center(
                child: CircularProgressIndicator(
                  color: RetroColors.goldOf(context),
                ),
              )
            : _buildContent(),
      ),
    );
  }

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

    return _buildHallOfFameList(hallOfFame);
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.emoji_events_outlined,
            size: 64,
            color: RetroColors.textMutedOf(context),
          ),
          const SizedBox(height: 16),
          Text(
            l10n.hofNoHeroes.toUpperCase(),
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: RetroColors.textSecondaryOf(context),
            ),
          ),
          const SizedBox(height: 12),
          Text(
            l10n.hofDefeatGlitchGod,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 12,
              color: RetroColors.textMutedOf(context),
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildHallOfFameList(HallOfFame hallOfFame) {
    final goldColor = RetroColors.goldOf(context);
    final borderColor = RetroColors.borderOf(context);

    return Container(
      decoration: BoxDecoration(
        color: RetroColors.panelBgOf(context),
        border: Border(
          top: BorderSide(color: goldColor, width: 3),
          left: BorderSide(color: goldColor, width: 3),
          bottom: BorderSide(color: borderColor, width: 3),
          right: BorderSide(color: borderColor, width: 3),
        ),
      ),
      margin: const EdgeInsets.all(12),
      child: Column(
        children: [
          // 헤더
          Container(
            padding: const EdgeInsets.symmetric(vertical: 10),
            decoration: BoxDecoration(
              color: goldColor.withValues(alpha: 0.2),
              border: Border(bottom: BorderSide(color: goldColor, width: 2)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.emoji_events, color: goldColor, size: 18),
                const SizedBox(width: 8),
                Text(
                  l10n.uiHallOfFame.toUpperCase(),
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    color: goldColor,
                    fontSize: 14,
                    letterSpacing: 1,
                  ),
                ),
                const SizedBox(width: 8),
                Icon(Icons.emoji_events, color: goldColor, size: 18),
              ],
            ),
          ),
          // 엔트리 목록
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: hallOfFame.entries.length,
              itemBuilder: (context, index) {
                final entry = hallOfFame.entries[index];
                return HallOfFameEntryCard(
                  entry: entry,
                  rank: index + 1,
                  onDeleteRequest: () => _confirmDelete(entry),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 삭제 확인 다이얼로그 (디버그 모드 전용)
  Future<void> _confirmDelete(HallOfFameEntry entry) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => RetroDialog(
        title: l10n.uiConfirm.toUpperCase(),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '${entry.characterName} (Lv.${entry.level})\n'
                '${l10n.uiConfirmDelete}',
                style: const TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 12,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    onPressed: () => Navigator.pop(context, false),
                    child: Text(l10n.uiCancel),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: RetroColors.hpOf(context),
                    ),
                    onPressed: () => Navigator.pop(context, true),
                    child: Text(l10n.uiDelete),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );

    if (confirmed == true && mounted) {
      await _deleteEntry(entry.id);
    }
  }

  /// 엔트리 삭제 실행
  Future<void> _deleteEntry(String id) async {
    final success = await _storage.deleteEntry(id);

    if (!mounted) return;

    if (success) {
      // 성공 시 목록 새로고침
      await _loadHallOfFame();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              l10n.uiDeleted,
              style: const TextStyle(fontFamily: 'PressStart2P', fontSize: 11),
            ),
            backgroundColor: RetroColors.mpOf(context),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } else {
      // 실패 시 에러 메시지
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              l10n.uiError,
              style: const TextStyle(fontFamily: 'PressStart2P', fontSize: 11),
            ),
            backgroundColor: RetroColors.hpOf(context),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }
}
