import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show KeyDownEvent, LogicalKeyboardKey;

import 'package:asciineverdie/data/game_text_l10n.dart' as game_l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/features/game/widgets/combat_log.dart';
import 'package:asciineverdie/src/features/game/widgets/desktop_character_panel.dart';
import 'package:asciineverdie/src/features/game/widgets/desktop_equipment_panel.dart';
import 'package:asciineverdie/src/features/game/widgets/desktop_quest_panel.dart';
import 'package:asciineverdie/src/features/game/widgets/task_progress_panel.dart';
import 'package:asciineverdie/src/shared/animation/ascii_animation_type.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 데스크톱 3패널 레이아웃
///
/// 웹/데스크톱용 레이아웃:
/// - 상단: 앱바 (타이틀, 치트/통계/도움말/설정 버튼)
/// - 중앙 상단: 태스크 진행 패널 (ASCII 애니메이션, 진행 바)
/// - 중앙 하단: 3패널 (캐릭터 | 장비+전투로그 | 퀘스트)
class DesktopGameLayout extends StatelessWidget {
  const DesktopGameLayout({
    super.key,
    required this.state,
    required this.combatLogEntries,
    required this.speedMultiplier,
    required this.onSpeedCycle,
    required this.isPaused,
    required this.onPauseToggle,
    this.specialAnimation,
    this.cheatsEnabled = false,
    this.onCheatTask,
    this.onCheatQuest,
    this.onCheatPlot,
    this.onShowStatistics,
    this.onShowHelp,
    this.onShowSettings,
  });

  final GameState state;
  final List<CombatLogEntry> combatLogEntries;
  final int speedMultiplier;
  final VoidCallback onSpeedCycle;
  final bool isPaused;
  final VoidCallback onPauseToggle;
  final AsciiAnimationType? specialAnimation;
  final bool cheatsEnabled;
  final VoidCallback? onCheatTask;
  final VoidCallback? onCheatQuest;
  final VoidCallback? onCheatPlot;
  final VoidCallback? onShowStatistics;
  final VoidCallback? onShowHelp;
  final VoidCallback? onShowSettings;

  @override
  Widget build(BuildContext context) {
    return Focus(
      autofocus: true,
      onKeyEvent: (node, event) => _handleKeyboardShortcut(event, context),
      child: Scaffold(
        backgroundColor: RetroColors.deepBrown,
        appBar: _buildAppBar(context),
        body: _buildMainContent(),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: RetroColors.darkBrown,
      title: Text(
        L10n.of(context).progressQuestTitle(state.traits.name),
        style: const TextStyle(
          fontFamily: 'PressStart2P',
          fontSize: 15,
          color: RetroColors.gold,
        ),
      ),
      actions: [
        if (cheatsEnabled) ...[
          IconButton(
            icon: const Text('L+1'),
            tooltip: L10n.of(context).levelUp,
            onPressed: onCheatTask,
          ),
          IconButton(
            icon: const Text('Q!'),
            tooltip: L10n.of(context).completeQuest,
            onPressed: onCheatQuest,
          ),
          IconButton(
            icon: const Text('P!'),
            tooltip: L10n.of(context).completePlot,
            onPressed: onCheatPlot,
          ),
        ],
        IconButton(
          icon: const Icon(Icons.bar_chart),
          tooltip: game_l10n.uiStatistics,
          onPressed: onShowStatistics,
        ),
        IconButton(
          icon: const Icon(Icons.help_outline),
          tooltip: game_l10n.uiHelp,
          onPressed: onShowHelp,
        ),
        IconButton(
          icon: const Icon(Icons.settings),
          tooltip: game_l10n.uiSettings,
          onPressed: onShowSettings,
        ),
      ],
    );
  }

  Widget _buildMainContent() {
    return Column(
      children: [
        TaskProgressPanel(
          progress: state.progress,
          speedMultiplier: speedMultiplier,
          onSpeedCycle: onSpeedCycle,
          isPaused: isPaused,
          onPauseToggle: onPauseToggle,
          specialAnimation: specialAnimation,
          weaponName: state.equipment.weapon,
          shieldName: state.equipment.shield,
          characterLevel: state.traits.level,
          monsterLevel: state.progress.currentTask.monsterLevel,
          monsterGrade: state.progress.currentTask.monsterGrade,
          monsterSize: state.progress.currentTask.monsterSize,
          latestCombatEvent:
              state.progress.currentCombat?.recentEvents.lastOrNull,
          raceId: state.traits.raceId,
        ),
        Expanded(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Expanded(flex: 2, child: DesktopCharacterPanel(state: state)),
              Expanded(
                flex: 3,
                child: DesktopEquipmentPanel(
                  state: state,
                  combatLogEntries: combatLogEntries,
                ),
              ),
              Expanded(flex: 2, child: DesktopQuestPanel(state: state)),
            ],
          ),
        ),
      ],
    );
  }

  /// 키보드 단축키 핸들러 (웹/데스크톱)
  /// Space: 일시정지/재개, S: 속도 변경, H: 도움말, Esc: 설정
  KeyEventResult _handleKeyboardShortcut(KeyEvent event, BuildContext context) {
    if (event is! KeyDownEvent) return KeyEventResult.ignored;

    final key = event.logicalKey;

    if (key == LogicalKeyboardKey.space) {
      onPauseToggle();
      return KeyEventResult.handled;
    }

    if (key == LogicalKeyboardKey.keyS) {
      onSpeedCycle();
      return KeyEventResult.handled;
    }

    if (key == LogicalKeyboardKey.keyH || key == LogicalKeyboardKey.f1) {
      onShowHelp?.call();
      return KeyEventResult.handled;
    }

    if (key == LogicalKeyboardKey.escape) {
      onShowSettings?.call();
      return KeyEventResult.handled;
    }

    if (key == LogicalKeyboardKey.keyI) {
      onShowStatistics?.call();
      return KeyEventResult.handled;
    }

    return KeyEventResult.ignored;
  }
}
