import 'package:flutter/material.dart';

import 'package:asciineverdie/src/core/notification/notification_service.dart';
import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/shared/animation/ascii_animation_type.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/features/game/pages/character_sheet_page.dart';
import 'package:asciineverdie/src/features/game/pages/combat_log_page.dart';
import 'package:asciineverdie/src/features/game/pages/equipment_page.dart';
import 'package:asciineverdie/src/features/game/pages/inventory_page.dart';
import 'package:asciineverdie/src/features/game/pages/quest_page.dart';
import 'package:asciineverdie/src/features/game/pages/skills_page.dart';
import 'package:asciineverdie/src/features/game/pages/story_page.dart';
import 'package:asciineverdie/src/features/game/widgets/carousel_nav_bar.dart';
import 'package:asciineverdie/src/features/game/widgets/combat_log.dart';
import 'package:asciineverdie/src/features/game/widgets/enhanced_animation_panel.dart';
import 'package:asciineverdie/src/features/game/widgets/mobile_options_menu.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 모바일 캐로셀 레이아웃
///
/// 모바일 앱용 레이아웃:
/// - 상단: 확장 애니메이션 패널 (ASCII 애니메이션, HP/MP, 버프, 몬스터 HP)
/// - 중앙: 캐로셀 (7개 페이지: 스킬, 인벤토리, 장비, 캐릭터시트, 전투로그, 스토리, 퀘스트)
/// - 하단: 네비게이션 바 (7개 버튼)
class MobileCarouselLayout extends StatefulWidget {
  const MobileCarouselLayout({
    super.key,
    required this.state,
    required this.combatLogEntries,
    required this.speedMultiplier,
    required this.onSpeedCycle,
    required this.isPaused,
    required this.onPauseToggle,
    required this.onSave,
    required this.onExit,
    required this.notificationService,
    required this.onLanguageChange,
    required this.onDeleteSaveAndNewGame,
    this.specialAnimation,
    this.bgmVolume = 0.7,
    this.sfxVolume = 0.8,
    this.onBgmVolumeChange,
    this.onSfxVolumeChange,
    this.onShowStatistics,
    this.onShowHelp,
    this.cheatsEnabled = false,
    this.onCheatTask,
    this.onCheatQuest,
    this.onCheatPlot,
    this.onCreateTestCharacter,
    this.autoReviveEndMs,
    this.speedBoostEndMs,
    this.isPaidUser = false,
    this.onSpeedBoostActivate,
    this.isSpeedBoostActive = false,
    this.onSetSpeed,
    this.adSpeedMultiplier = 5,
    this.has2xUnlocked = false,
  });

  final GameState state;
  final List<CombatLogEntry> combatLogEntries;
  final int speedMultiplier;
  final VoidCallback onSpeedCycle;

  /// 특정 속도로 직접 설정 (옵션 메뉴용)
  final void Function(int speed)? onSetSpeed;
  final bool isPaused;
  final VoidCallback onPauseToggle;
  final VoidCallback onSave;
  final VoidCallback onExit;
  final NotificationService notificationService;
  final void Function(String locale) onLanguageChange;
  final VoidCallback onDeleteSaveAndNewGame;
  final AsciiAnimationType? specialAnimation;

  /// BGM 볼륨 (0.0 ~ 1.0)
  final double bgmVolume;

  /// SFX 볼륨 (0.0 ~ 1.0)
  final double sfxVolume;

  /// BGM 볼륨 변경 콜백
  final void Function(double volume)? onBgmVolumeChange;

  /// SFX 볼륨 변경 콜백
  final void Function(double volume)? onSfxVolumeChange;

  /// 통계 표시 콜백
  final VoidCallback? onShowStatistics;

  /// 도움말 표시 콜백
  final VoidCallback? onShowHelp;

  /// 치트 모드 활성화 여부
  final bool cheatsEnabled;

  /// 치트: 태스크 완료
  final VoidCallback? onCheatTask;

  /// 치트: 퀘스트 완료
  final VoidCallback? onCheatQuest;

  /// 치트: 액트(플롯) 완료
  final VoidCallback? onCheatPlot;

  /// 테스트 캐릭터 생성 콜백 (디버그 모드 전용)
  final Future<void> Function()? onCreateTestCharacter;

  /// 자동부활 버프 종료 시점 (elapsedMs 기준)
  final int? autoReviveEndMs;

  /// 5배속 버프 종료 시점 (elapsedMs 기준)
  final int? speedBoostEndMs;

  /// 유료 유저 여부
  final bool isPaidUser;

  /// 광고 배속 활성화 콜백 (광고 시청)
  final VoidCallback? onSpeedBoostActivate;

  /// 배속 부스트 활성화 여부
  final bool isSpeedBoostActive;

  /// 광고 배속 배율 (릴리즈: 5x, 디버그빌드+디버그모드: 20x)
  final int adSpeedMultiplier;

  /// 2x 배속 해금 여부 (명예의 전당에 캐릭터가 있으면 true)
  final bool has2xUnlocked;

  @override
  State<MobileCarouselLayout> createState() => _MobileCarouselLayoutState();
}

class _MobileCarouselLayoutState extends State<MobileCarouselLayout> {
  late PageController _pageController;
  int _currentPage = CarouselPage.character.index; // 기본: 캐릭터시트

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentPage);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _onPageChanged(int page) {
    setState(() {
      _currentPage = page;
    });
  }

  void _onNavPageSelected(int page) {
    _pageController.animateToPage(
      page,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  void _openOptionsMenu(BuildContext context) {
    showMobileOptionsMenu(
      context,
      MobileOptionsConfig(
        isPaused: widget.isPaused,
        speedMultiplier: widget.speedMultiplier,
        bgmVolume: widget.bgmVolume,
        sfxVolume: widget.sfxVolume,
        cheatsEnabled: widget.cheatsEnabled,
        isPaidUser: widget.isPaidUser,
        isSpeedBoostActive: widget.isSpeedBoostActive,
        adSpeedMultiplier: widget.adSpeedMultiplier,
        notificationService: widget.notificationService,
        onPauseToggle: widget.onPauseToggle,
        onSpeedCycle: widget.onSpeedCycle,
        onSave: widget.onSave,
        onExit: widget.onExit,
        onLanguageChange: widget.onLanguageChange,
        onDeleteSaveAndNewGame: widget.onDeleteSaveAndNewGame,
        onBgmVolumeChange: widget.onBgmVolumeChange,
        onSfxVolumeChange: widget.onSfxVolumeChange,
        onShowStatistics: widget.onShowStatistics,
        onShowHelp: widget.onShowHelp,
        onCheatTask: widget.onCheatTask,
        onCheatQuest: widget.onCheatQuest,
        onCheatPlot: widget.onCheatPlot,
        onCreateTestCharacter: widget.onCreateTestCharacter,
        onSpeedBoostActivate: widget.onSpeedBoostActivate,
        onSetSpeed: widget.onSetSpeed,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final state = widget.state;
    final background = RetroColors.backgroundOf(context);
    final panelBg = RetroColors.panelBgOf(context);
    final gold = RetroColors.goldOf(context);

    return Scaffold(
      backgroundColor: background,
      appBar: AppBar(
        backgroundColor: panelBg,
        title: Text(
          L10n.of(context).progressQuestTitle(state.traits.name),
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 14,
            color: gold,
          ),
        ),
        actions: [
          // 옵션 버튼
          IconButton(
            icon: Icon(Icons.settings, color: gold),
            onPressed: () => _openOptionsMenu(context),
            tooltip: l10n.menuOptions,
          ),
        ],
      ),
      body: SafeArea(
        top: false, // AppBar가 상단 처리
        child: Column(
          children: [
            // 상단: 확장 애니메이션 패널
            EnhancedAnimationPanel(
              progress: state.progress,
              stats: state.stats,
              skillSystem: state.skillSystem,
              speedMultiplier: widget.speedMultiplier,
              onSpeedCycle: widget.onSpeedCycle,
              isPaused: widget.isPaused,
              onPauseToggle: widget.onPauseToggle,
              specialAnimation: widget.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,
              weaponRarity: state.equipment.weaponItem.rarity,
              autoReviveEndMs: widget.autoReviveEndMs,
              speedBoostEndMs: widget.speedBoostEndMs,
              isPaidUser: widget.isPaidUser,
              onSpeedBoostActivate: widget.onSpeedBoostActivate,
              isSpeedBoostActive: widget.isSpeedBoostActive,
              adSpeedMultiplier: widget.adSpeedMultiplier,
            ),

            // 중앙: 캐로셀 (PageView)
            Expanded(
              child: PageView(
                controller: _pageController,
                onPageChanged: _onPageChanged,
                children: [
                  // 0: 스킬
                  SkillsPage(
                    skillBook: state.skillBook,
                    skillSystem: state.skillSystem,
                  ),

                  // 1: 인벤토리
                  InventoryPage(
                    inventory: state.inventory,
                    potionInventory: state.potionInventory,
                    encumbrance: state.progress.encumbrance,
                  ),

                  // 2: 장비
                  EquipmentPage(equipment: state.equipment),

                  // 3: 캐릭터시트 (기본)
                  CharacterSheetPage(
                    traits: state.traits,
                    stats: state.stats,
                    exp: state.progress.exp,
                  ),

                  // 4: 전투로그
                  CombatLogPage(entries: widget.combatLogEntries),

                  // 5: 퀘스트
                  QuestPage(
                    questHistory: state.progress.questHistory,
                    quest: state.progress.quest,
                  ),

                  // 6: 스토리
                  StoryPage(
                    plotStageCount: state.progress.plotStageCount,
                    plot: state.progress.plot,
                  ),
                ],
              ),
            ),

            // 하단: 네비게이션 바
            CarouselNavBar(
              currentPage: _currentPage,
              onPageSelected: _onNavPageSelected,
            ),
          ],
        ),
      ),
    );
  }
}
