import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/src/shared/l10n/game_data_l10n.dart';
import 'package:asciineverdie/src/core/model/equipment_slot.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/item_stats.dart';
import 'package:asciineverdie/src/features/game/widgets/death_buttons.dart';
import 'package:asciineverdie/src/features/game/widgets/death_combat_log.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 사망 오버레이 위젯
///
/// 플레이어 사망 시 표시되는 전체 화면 오버레이
/// - 무료 부활: HP 50%, 아이템 희생
/// - 광고 부활: HP 100%, 아이템 복구, 10분 자동부활 버프
class DeathOverlay extends StatelessWidget {
  const DeathOverlay({
    super.key,
    required this.deathInfo,
    required this.traits,
    required this.onResurrect,
    this.onAdRevive,
    this.isPaidUser = false,
  });

  /// 사망 정보
  final DeathInfo deathInfo;

  /// 캐릭터 특성 (이름, 직업 등)
  final Traits traits;

  /// 무료 부활 버튼 콜백 (HP 50%, 아이템 희생)
  final VoidCallback onResurrect;

  /// 광고 부활 버튼 콜백 (HP 100% + 아이템 복구 + 10분 자동부활)
  /// null이면 광고 부활 버튼 숨김
  final VoidCallback? onAdRevive;

  /// 유료 유저 여부 (광고 아이콘 표시용)
  final bool isPaidUser;

  @override
  Widget build(BuildContext context) {
    // 테마 인식 색상 (Theme-aware colors)
    final hpColor = RetroColors.hpOf(context);
    final hpDark = RetroColors.hpDarkOf(context);
    final panelBg = RetroColors.panelBgOf(context);
    final borderColor = RetroColors.borderOf(context);

    return Material(
      color: Colors.black.withValues(alpha: 0.9),
      child: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 420),
          margin: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: panelBg,
            border: Border(
              top: BorderSide(color: hpColor, width: 4),
              left: BorderSide(color: hpColor, width: 4),
              bottom: BorderSide(color: borderColor, width: 4),
              right: BorderSide(color: borderColor, width: 4),
            ),
            boxShadow: [
              BoxShadow(
                color: hpColor.withValues(alpha: 0.5),
                blurRadius: 30,
                spreadRadius: 5,
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 헤더 바
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 8,
                ),
                decoration: BoxDecoration(
                  color: hpColor.withValues(alpha: 0.3),
                  border: Border(bottom: BorderSide(color: hpColor, width: 2)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('☠', style: TextStyle(fontSize: 20, color: hpColor)),
                    const SizedBox(width: 8),
                    Text(
                      'GAME OVER',
                      style: TextStyle(
                        fontFamily: 'PressStart2P',
                        fontSize: 15,
                        color: hpColor,
                        letterSpacing: 2,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text('☠', style: TextStyle(fontSize: 20, color: hpColor)),
                  ],
                ),
              ),
              // 본문 (스크롤 가능)
              Flexible(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 사망 타이틀
                      _buildDeathTitle(context),
                      const SizedBox(height: 16),

                      // 캐릭터 정보
                      _buildCharacterInfo(context),
                      const SizedBox(height: 16),

                      // 사망 원인
                      _buildDeathCause(context),
                      const SizedBox(height: 20),

                      // 구분선
                      _buildRetroDivider(hpColor, hpDark),
                      const SizedBox(height: 16),

                      // 상실 정보
                      _buildLossInfo(context),

                      // 전투 로그 (있는 경우만 표시)
                      if (deathInfo.lastCombatEvents.isNotEmpty) ...[
                        const SizedBox(height: 16),
                        _buildRetroDivider(hpColor, hpDark),
                        const SizedBox(height: 8),
                        DeathCombatLog(events: deathInfo.lastCombatEvents),
                      ],

                      const SizedBox(height: 24),

                      // 일반 부활 버튼 (HP 50%, 아이템 희생)
                      DeathResurrectButton(onResurrect: onResurrect),

                      // 광고 부활 버튼 (HP 100% + 아이템 복구 + 10분 자동부활)
                      if (onAdRevive != null) ...[
                        const SizedBox(height: 12),
                        DeathAdReviveButton(
                          onAdRevive: onAdRevive!,
                          deathInfo: deathInfo,
                          isPaidUser: isPaidUser,
                        ),
                      ],
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 레트로 스타일 구분선
  Widget _buildRetroDivider(Color hpColor, Color hpDark) {
    return Container(
      height: 2,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.transparent,
            hpDark,
            hpColor,
            hpDark,
            Colors.transparent,
          ],
        ),
      ),
    );
  }

  Widget _buildDeathTitle(BuildContext context) {
    final hpColor = RetroColors.hpOf(context);
    final hpDark = RetroColors.hpDarkOf(context);

    return Column(
      children: [
        // ASCII 스컬 (더 큰 버전)
        Text(
          '    _____ \n'
          '   /     \\\n'
          '  | () () |\n'
          '   \\  ^  /\n'
          '    ||||| ',
          style: TextStyle(
            fontFamily: 'JetBrainsMono',
            fontSize: 17,
            color: hpColor,
            height: 1.0,
          ),
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 12),
        Text(
          l10n.deathYouDied.toUpperCase(),
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 16,
            color: hpColor,
            letterSpacing: 2,
            shadows: [
              const Shadow(color: Colors.black, blurRadius: 4),
              Shadow(color: hpDark, blurRadius: 8),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildCharacterInfo(BuildContext context) {
    final surface = RetroColors.surfaceOf(context);
    final borderLight = RetroColors.borderLightOf(context);
    final gold = RetroColors.goldOf(context);
    final textPrimary = RetroColors.textPrimaryOf(context);

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: surface.withValues(alpha: 0.5),
        border: Border.all(color: borderLight, width: 1),
      ),
      child: Column(
        children: [
          Text(
            traits.name,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: gold,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            'Lv.${deathInfo.levelAtDeath} ${GameDataL10n.getKlassName(context, traits.klass)}',
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 13,
              color: textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeathCause(BuildContext context) {
    final causeText = _getDeathCauseText();
    final hpColor = RetroColors.hpOf(context);
    final hpDark = RetroColors.hpDarkOf(context);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: hpDark.withValues(alpha: 0.3),
        border: Border.all(color: hpColor.withValues(alpha: 0.5)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('⚔', style: TextStyle(fontSize: 18, color: hpColor)),
          const SizedBox(width: 8),
          Flexible(
            child: Text(
              causeText,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 14,
                color: hpColor,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  String _getDeathCauseText() {
    return switch (deathInfo.cause) {
      DeathCause.monster => l10n.deathKilledBy(deathInfo.killerName),
      DeathCause.selfDamage => l10n.deathSelfInflicted,
      DeathCause.environment => l10n.deathEnvironmentalHazard,
    };
  }

  Widget _buildLossInfo(BuildContext context) {
    final hasLostItem = deathInfo.lostItemName != null;
    final hpColor = RetroColors.hpOf(context);
    final hpDark = RetroColors.hpDarkOf(context);
    final muted = RetroColors.textMutedOf(context);
    final expColor = RetroColors.expOf(context);
    final gold = RetroColors.goldOf(context);

    // 희귀도에 따른 아이템 이름 색상
    final itemRarityColor = _getRarityColor(deathInfo.lostItemRarity);

    return Column(
      children: [
        // 제물로 바친 아이템 표시
        if (hasLostItem) ...[
          Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: hpDark.withValues(alpha: 0.2),
              border: Border.all(color: hpColor.withValues(alpha: 0.4)),
            ),
            child: Row(
              children: [
                const Text('🔥', style: TextStyle(fontSize: 20)),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        l10n.deathSacrificedToResurrect.toUpperCase(),
                        style: TextStyle(
                          fontFamily: 'PressStart2P',
                          fontSize: 13,
                          color: muted,
                        ),
                      ),
                      const SizedBox(height: 4),
                      // 슬롯명 (회색) + 아이템명 (희귀도 색상)
                      Text.rich(
                        TextSpan(
                          children: [
                            TextSpan(
                              text:
                                  '[${_getSlotName(deathInfo.lostItemSlot)}] ',
                              style: TextStyle(color: muted),
                            ),
                            TextSpan(
                              text: deathInfo.lostItemName!,
                              style: TextStyle(color: itemRarityColor),
                            ),
                          ],
                        ),
                        style: const TextStyle(
                          fontFamily: 'PressStart2P',
                          fontSize: 13,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
        ] else ...[
          _buildInfoRow(
            context,
            asciiIcon: '✓',
            label: l10n.deathEquipment,
            value: l10n.deathNoSacrificeNeeded,
            valueColor: expColor,
          ),
          const SizedBox(height: 8),
        ],
        _buildInfoRow(
          context,
          asciiIcon: '💰',
          label: l10n.deathCoinRemaining,
          value: _formatGold(deathInfo.goldAtDeath),
          valueColor: gold,
        ),
      ],
    );
  }

  Widget _buildInfoRow(
    BuildContext context, {
    required String asciiIcon,
    required String label,
    required String value,
    required Color valueColor,
  }) {
    final muted = RetroColors.textMutedOf(context);

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Text(asciiIcon, style: TextStyle(fontSize: 18, color: valueColor)),
            const SizedBox(width: 8),
            Text(
              label,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 13,
                color: muted,
              ),
            ),
          ],
        ),
        Text(
          value,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: valueColor,
          ),
        ),
      ],
    );
  }

  String _formatGold(int gold) {
    if (gold >= 1000000) {
      return '${(gold / 1000000).toStringAsFixed(1)}M';
    } else if (gold >= 1000) {
      return '${(gold / 1000).toStringAsFixed(1)}K';
    }
    return gold.toString();
  }

  /// 장비 슬롯 이름 반환
  String _getSlotName(EquipmentSlot? slot) {
    if (slot == null) return '';
    return switch (slot) {
      EquipmentSlot.weapon => l10n.slotWeapon,
      EquipmentSlot.shield => l10n.slotShield,
      EquipmentSlot.helm => l10n.slotHelm,
      EquipmentSlot.hauberk => l10n.slotHauberk,
      EquipmentSlot.brassairts => l10n.slotBrassairts,
      EquipmentSlot.vambraces => l10n.slotVambraces,
      EquipmentSlot.gauntlets => l10n.slotGauntlets,
      EquipmentSlot.gambeson => l10n.slotGambeson,
      EquipmentSlot.cuisses => l10n.slotCuisses,
      EquipmentSlot.greaves => l10n.slotGreaves,
      EquipmentSlot.sollerets => l10n.slotSollerets,
    };
  }

  /// 희귀도에 따른 색상 반환
  Color _getRarityColor(ItemRarity? rarity) {
    if (rarity == null) return Colors.grey;
    return switch (rarity) {
      ItemRarity.common => Colors.grey,
      ItemRarity.uncommon => Colors.green,
      ItemRarity.rare => Colors.blue,
      ItemRarity.epic => Colors.purple,
      ItemRarity.legendary => Colors.orange,
    };
  }
}
