import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as game_l10n;
import 'package:asciineverdie/data/skill_data.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/core/model/skill.dart';
import 'package:asciineverdie/src/features/game/widgets/desktop_panel_widgets.dart';
import 'package:asciineverdie/src/features/game/widgets/hp_mp_bar.dart';
import 'package:asciineverdie/src/features/game/widgets/stats_panel.dart';
import 'package:asciineverdie/src/features/game/widgets/active_buff_panel.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 데스크톱 좌측 패널: Character Sheet
///
/// Traits, Stats, HP/MP, Experience, SpellBook, Buffs 표시
class DesktopCharacterPanel extends StatelessWidget {
  const DesktopCharacterPanel({super.key, required this.state});

  final GameState state;

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);
    return Card(
      margin: const EdgeInsets.all(4),
      color: RetroColors.panelBg,
      shape: RoundedRectangleBorder(
        side: const BorderSide(color: RetroColors.panelBorderOuter, width: 2),
        borderRadius: BorderRadius.circular(0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          DesktopPanelHeader(title: l10n.characterSheet),
          DesktopSectionHeader(title: l10n.traits),
          _TraitsList(state: state),
          DesktopSectionHeader(title: l10n.stats),
          Expanded(flex: 2, child: StatsPanel(stats: state.stats)),
          HpMpBar(
            hpCurrent:
                state.progress.currentCombat?.playerStats.hpCurrent ??
                state.stats.hp,
            hpMax:
                state.progress.currentCombat?.playerStats.hpMax ??
                state.stats.hpMax,
            mpCurrent:
                state.progress.currentCombat?.playerStats.mpCurrent ??
                state.stats.mp,
            mpMax:
                state.progress.currentCombat?.playerStats.mpMax ??
                state.stats.mpMax,
            monsterHpCurrent:
                state.progress.currentCombat?.monsterStats.hpCurrent,
            monsterHpMax: state.progress.currentCombat?.monsterStats.hpMax,
            monsterName: state.progress.currentCombat?.monsterStats.name,
            monsterLevel: state.progress.currentCombat?.monsterStats.level,
          ),
          DesktopSectionHeader(title: l10n.experience),
          DesktopSegmentProgressBar(
            position: state.progress.exp.position,
            max: state.progress.exp.max,
            color: Colors.blue,
            tooltip:
                '${state.progress.exp.position} / ${state.progress.exp.max}',
          ),
          DesktopSectionHeader(title: l10n.spellBook),
          Expanded(flex: 3, child: _SkillsList(state: state)),
          DesktopSectionHeader(title: game_l10n.uiBuffs),
          Expanded(
            child: ActiveBuffPanel(
              activeBuffs: state.skillSystem.activeBuffs,
              currentMs: state.skillSystem.elapsedMs,
            ),
          ),
        ],
      ),
    );
  }
}

/// Traits 목록 위젯
class _TraitsList extends StatelessWidget {
  const _TraitsList({required this.state});

  final GameState state;

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);
    final traits = [
      (l10n.traitName, state.traits.name),
      (l10n.traitRace, GameDataL10n.getRaceName(context, state.traits.race)),
      (l10n.traitClass, GameDataL10n.getKlassName(context, state.traits.klass)),
      (l10n.traitLevel, '${state.traits.level}'),
    ];

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      child: Column(
        children: traits.map((t) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 1),
            child: Row(
              children: [
                SizedBox(
                  width: 50,
                  child: Text(
                    t.$1.toUpperCase(),
                    style: const TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 13,
                      color: RetroColors.textDisabled,
                    ),
                  ),
                ),
                Expanded(
                  child: Text(
                    t.$2,
                    style: const TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 14,
                      color: RetroColors.textLight,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }
}

/// 통합 스킬 목록 (SkillBook 기반)
class _SkillsList extends StatelessWidget {
  const _SkillsList({required this.state});

  final GameState state;

  @override
  Widget build(BuildContext context) {
    if (state.skillBook.skills.isEmpty) {
      return Center(
        child: Text(
          L10n.of(context).noSpellsYet,
          style: const TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: RetroColors.textDisabled,
          ),
        ),
      );
    }

    return ListView.builder(
      itemCount: state.skillBook.skills.length,
      padding: const EdgeInsets.symmetric(horizontal: 8),
      itemBuilder: (context, index) {
        final skillEntry = state.skillBook.skills[index];
        final skill = SkillData.getSkillBySpellName(skillEntry.name);
        final skillName = GameDataL10n.getSpellName(context, skillEntry.name);

        final skillState = skill != null
            ? state.skillSystem.getSkillState(skill.id)
            : null;
        final isOnCooldown =
            skillState != null &&
            !skillState.isReady(state.skillSystem.elapsedMs, skill!.cooldownMs);

        return _SkillRow(
          skillName: skillName,
          rank: skillEntry.rank,
          skill: skill,
          isOnCooldown: isOnCooldown,
        );
      },
    );
  }
}

/// 스킬 행 위젯
class _SkillRow extends StatelessWidget {
  const _SkillRow({
    required this.skillName,
    required this.rank,
    required this.skill,
    required this.isOnCooldown,
  });

  final String skillName;
  final String rank;
  final Skill? skill;
  final bool isOnCooldown;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 1),
      child: Row(
        children: [
          _buildTypeIcon(),
          const SizedBox(width: 4),
          Expanded(
            child: Text(
              skillName,
              style: TextStyle(
                fontSize: 16,
                color: isOnCooldown ? Colors.grey : null,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          if (isOnCooldown)
            const Icon(Icons.hourglass_empty, size: 10, color: Colors.orange),
          const SizedBox(width: 4),
          Text(
            rank,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  Widget _buildTypeIcon() {
    if (skill == null) {
      return const SizedBox(width: 12);
    }

    final (IconData icon, Color color) = switch (skill!.type) {
      SkillType.attack => (Icons.flash_on, Colors.red),
      SkillType.heal => (Icons.favorite, Colors.green),
      SkillType.buff => (Icons.arrow_upward, Colors.blue),
      SkillType.debuff => (Icons.arrow_downward, Colors.purple),
    };

    return Icon(icon, size: 12, color: color);
  }
}
