import 'package:flutter/material.dart';

import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/shared/l10n/game_data_l10n.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 승리 크레딧 콘텐츠(victory credit content) 위젯
///
/// 영웅 정보, 통계, ASCII 아트, 크레딧 텍스트,
/// 명예의 전당 버튼 등 스크롤되는 콘텐츠를 구성한다.
class VictoryCreditContent extends StatelessWidget {
  const VictoryCreditContent({
    super.key,
    required this.traits,
    required this.stats,
    required this.progress,
    required this.elapsedMs,
    required this.onComplete,
  });

  final Traits traits;
  final Stats stats;
  final ProgressState progress;
  final int elapsedMs;

  /// 엔딩 완료 콜백(callback) - 명예의 전당으로 이동
  final VoidCallback onComplete;

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);
    final gold = RetroColors.goldOf(context);
    final textPrimary = RetroColors.textPrimaryOf(context);

    return Center(
      child: Container(
        constraints: const BoxConstraints(maxWidth: 500),
        padding: const EdgeInsets.symmetric(horizontal: 24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildVictoryAsciiArt(gold),
            const SizedBox(height: 60),

            // 축하 메시지(congratulations)
            Text(
              l10n.endingCongratulations,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 16,
                color: gold,
                letterSpacing: 2,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              l10n.endingGameComplete,
              style: TextStyle(
                fontFamily: 'JetBrainsMono',
                fontSize: 18,
                color: textPrimary,
              ),
            ),
            const SizedBox(height: 80),

            _buildSectionTitle(l10n.endingTheHero, gold),
            const SizedBox(height: 20),
            _buildHeroInfo(context),
            const SizedBox(height: 80),

            _buildSectionTitle(l10n.endingJourneyStats, gold),
            const SizedBox(height: 20),
            _buildStatistics(context),
            const SizedBox(height: 80),

            _buildSectionTitle(l10n.endingFinalStats, gold),
            const SizedBox(height: 20),
            _buildFinalStats(context),
            const SizedBox(height: 100),

            _buildTrophyAsciiArt(gold),
            const SizedBox(height: 60),

            _buildSectionTitle(l10n.endingCredits, gold),
            const SizedBox(height: 20),
            _buildCredits(context),
            const SizedBox(height: 100),

            _buildTheEnd(context, gold),
            const SizedBox(height: 60),

            _buildHallOfFameButton(context, gold),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  Widget _buildVictoryAsciiArt(Color gold) {
    const asciiArt = '''
╔═══════════════════════════════════════════╗
║                                           ║
║   ██╗   ██╗██╗ ██████╗████████╗ ██████╗   ║
║   ██║   ██║██║██╔════╝╚══██╔══╝██╔═══██╗  ║
║   ██║   ██║██║██║        ██║   ██║   ██║  ║
║   ╚██╗ ██╔╝██║██║        ██║   ██║   ██║  ║
║    ╚████╔╝ ██║╚██████╗   ██║   ╚██████╔╝  ║
║     ╚═══╝  ╚═╝ ╚═════╝   ╚═╝    ╚═════╝   ║
║                                           ║
║   ██████╗ ██╗   ██╗                       ║
║   ██╔══██╗╚██╗ ██╔╝                       ║
║   ██████╔╝ ╚████╔╝                        ║
║   ██╔══██╗  ╚██╔╝                         ║
║   ██║  ██║   ██║                          ║
║   ╚═╝  ╚═╝   ╚═╝                          ║
║                                           ║
╚═══════════════════════════════════════════╝''';

    return Text(
      asciiArt,
      style: TextStyle(
        fontFamily: 'JetBrainsMono',
        fontSize: 14,
        color: gold,
        height: 1.0,
      ),
      textAlign: TextAlign.center,
    );
  }

  Widget _buildSectionTitle(String title, Color gold) {
    return Column(
      children: [
        Text(
          '═══════════════════',
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: gold.withValues(alpha: 0.5),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          title,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 15,
            color: gold,
            letterSpacing: 2,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '═══════════════════',
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: gold.withValues(alpha: 0.5),
          ),
        ),
      ],
    );
  }

  Widget _buildHeroInfo(BuildContext context) {
    final l10n = L10n.of(context);
    final gold = RetroColors.goldOf(context);
    final textPrimary = RetroColors.textPrimaryOf(context);
    final textMuted = RetroColors.textMutedOf(context);

    return Column(
      children: [
        Text(
          traits.name,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 18,
            color: gold,
          ),
        ),
        const SizedBox(height: 12),
        Text(
          l10n.endingLevelFormat(traits.level),
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: textPrimary,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '${GameDataL10n.getRaceName(context, traits.race)} '
          '${GameDataL10n.getKlassName(context, traits.klass)}',
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: textMuted,
          ),
        ),
      ],
    );
  }

  Widget _buildStatistics(BuildContext context) {
    final l10n = L10n.of(context);
    final textPrimary = RetroColors.textPrimaryOf(context);
    final exp = RetroColors.expOf(context);

    // 플레이 시간(play time) 포맷
    final playTime = Duration(milliseconds: elapsedMs);
    final hours = playTime.inHours;
    final minutes = playTime.inMinutes % 60;
    final seconds = playTime.inSeconds % 60;
    final playTimeStr =
        '${hours.toString().padLeft(2, '0')}:'
        '${minutes.toString().padLeft(2, '0')}:'
        '${seconds.toString().padLeft(2, '0')}';

    return Column(
      children: [
        _buildStatLine(
          l10n.endingMonstersSlain,
          '${progress.monstersKilled}',
          textPrimary,
          exp,
        ),
        const SizedBox(height: 8),
        _buildStatLine(
          l10n.endingQuestsCompleted,
          '${progress.questCount}',
          textPrimary,
          exp,
        ),
        const SizedBox(height: 8),
        _buildStatLine(
          l10n.endingPlayTime,
          playTimeStr,
          textPrimary,
          textPrimary,
        ),
      ],
    );
  }

  Widget _buildStatLine(
    String label,
    String value,
    Color labelColor,
    Color valueColor,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          '$label: ',
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: labelColor.withValues(alpha: 0.7),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: valueColor,
          ),
        ),
      ],
    );
  }

  Widget _buildFinalStats(BuildContext context) {
    final textPrimary = RetroColors.textPrimaryOf(context);

    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildStatBox('STR', '${stats.str}', textPrimary),
            const SizedBox(width: 16),
            _buildStatBox('CON', '${stats.con}', textPrimary),
            const SizedBox(width: 16),
            _buildStatBox('DEX', '${stats.dex}', textPrimary),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildStatBox('INT', '${stats.intelligence}', textPrimary),
            const SizedBox(width: 16),
            _buildStatBox('WIS', '${stats.wis}', textPrimary),
            const SizedBox(width: 16),
            _buildStatBox('CHA', '${stats.cha}', textPrimary),
          ],
        ),
      ],
    );
  }

  Widget _buildStatBox(String label, String value, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 15,
            color: color.withValues(alpha: 0.5),
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 15,
            color: color,
          ),
        ),
      ],
    );
  }

  Widget _buildTrophyAsciiArt(Color gold) {
    const trophy = '''
 ____________
 '._==_==_=_.'
 .-\\:      /-.
 | (|:.    |) |
 '-|:.    |-'
 \\::.   /
 '::. .'
 ) (
 _.' '._
 '-------' ''';

    return Text(
      trophy,
      style: TextStyle(
        fontFamily: 'JetBrainsMono',
        fontSize: 17,
        color: gold,
        height: 1.0,
      ),
      textAlign: TextAlign.center,
    );
  }

  Widget _buildCredits(BuildContext context) {
    final l10n = L10n.of(context);
    final textPrimary = RetroColors.textPrimaryOf(context);
    final textMuted = RetroColors.textMutedOf(context);
    final gold = RetroColors.goldOf(context);

    return Column(
      children: [
        Text(
          l10n.appTitle,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 15,
            color: gold,
          ),
        ),
        const SizedBox(height: 16),
        Text(
          l10n.endingThankYou,
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: textPrimary,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          l10n.endingLegendLivesOn,
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 15,
            color: textMuted,
            fontStyle: FontStyle.italic,
          ),
        ),
      ],
    );
  }

  Widget _buildTheEnd(BuildContext context, Color gold) {
    const theEnd = '''
████████╗██╗  ██╗███████╗    ███████╗███╗   ██╗██████╗
 ╚══██╔══╝██║  ██║██╔════╝    ██╔════╝████╗  ██║██╔══██╗
    ██║   ███████║█████╗      █████╗  ██╔██╗ ██║██║  ██║
    ██║   ██╔══██║██╔══╝      ██╔══╝  ██║╚██╗██║██║  ██║
    ██║   ██║  ██║███████╗    ███████╗██║ ╚████║██████╔╝
    ╚═╝   ╚═╝  ╚═╝╚══════╝    ╚══════╝╚═╝  ╚═══╝╚═════╝ ''';

    // FittedBox로 감싸서 화면 너비에 맞게 자동 스케일링(scaling)
    return FittedBox(
      fit: BoxFit.scaleDown,
      child: Text(
        theEnd,
        style: TextStyle(
          fontFamily: 'JetBrainsMono',
          fontSize: 12,
          color: gold,
          height: 1.0,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 명예의 전당(Hall of Fame) 버튼
  Widget _buildHallOfFameButton(BuildContext context, Color gold) {
    final l10n = L10n.of(context);

    return Column(
      children: [
        Text(
          l10n.endingHallOfFameLine1,
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: gold.withValues(alpha: 0.7),
          ),
        ),
        const SizedBox(height: 4),
        Text(
          l10n.endingHallOfFameLine2,
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: gold.withValues(alpha: 0.7),
          ),
        ),
        const SizedBox(height: 24),
        SizedBox(
          width: 280,
          height: 56,
          child: ElevatedButton(
            onPressed: onComplete,
            style: ElevatedButton.styleFrom(
              backgroundColor: gold,
              foregroundColor: Colors.black,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              elevation: 8,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.emoji_events, size: 24),
                const SizedBox(width: 12),
                Text(
                  l10n.endingHallOfFameButton,
                  style: const TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
