import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/features/game/widgets/dialogs/retro_confirm_dialog.dart';
import 'package:asciineverdie/src/features/game/widgets/dialogs/retro_select_dialog.dart';
import 'package:asciineverdie/src/features/game/widgets/dialogs/retro_sound_dialog.dart';
import 'package:asciineverdie/src/features/game/widgets/menu/retro_menu_widgets.dart';
import 'package:asciineverdie/src/core/notification/notification_service.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_widgets.dart';

/// 모바일 옵션 메뉴 설정
class MobileOptionsConfig {
  const MobileOptionsConfig({
    required this.isPaused,
    required this.speedMultiplier,
    required this.bgmVolume,
    required this.sfxVolume,
    required this.cheatsEnabled,
    required this.isPaidUser,
    required this.isSpeedBoostActive,
    required this.adSpeedMultiplier,
    required this.notificationService,
    required this.onPauseToggle,
    required this.onSpeedCycle,
    required this.onSave,
    required this.onExit,
    required this.onLanguageChange,
    required this.onDeleteSaveAndNewGame,
    this.onBgmVolumeChange,
    this.onSfxVolumeChange,
    this.onShowStatistics,
    this.onShowHelp,
    this.onCheatTask,
    this.onCheatQuest,
    this.onCheatPlot,
    this.onCreateTestCharacter,
    this.onSpeedBoostActivate,
    this.onSetSpeed,
  });

  final bool isPaused;
  final int speedMultiplier;
  final double bgmVolume;
  final double sfxVolume;
  final bool cheatsEnabled;
  final bool isPaidUser;
  final bool isSpeedBoostActive;
  final int adSpeedMultiplier;
  final NotificationService notificationService;
  final VoidCallback onPauseToggle;
  final VoidCallback onSpeedCycle;
  final VoidCallback onSave;
  final VoidCallback onExit;
  final void Function(String locale) onLanguageChange;
  final VoidCallback onDeleteSaveAndNewGame;
  final void Function(double volume)? onBgmVolumeChange;
  final void Function(double volume)? onSfxVolumeChange;
  final VoidCallback? onShowStatistics;
  final VoidCallback? onShowHelp;
  final VoidCallback? onCheatTask;
  final VoidCallback? onCheatQuest;
  final VoidCallback? onCheatPlot;
  final Future<void> Function()? onCreateTestCharacter;
  final VoidCallback? onSpeedBoostActivate;
  final void Function(int speed)? onSetSpeed;
}

/// 모바일 옵션 메뉴 표시
void showMobileOptionsMenu(BuildContext context, MobileOptionsConfig config) {
  final background = RetroColors.backgroundOf(context);
  final border = RetroColors.borderOf(context);

  showModalBottomSheet<void>(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    constraints: BoxConstraints(
      maxHeight: MediaQuery.of(context).size.height * 0.75,
    ),
    builder: (context) => Container(
      decoration: BoxDecoration(
        color: background,
        border: Border.all(color: border, width: 2),
        borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 핸들 바
            Padding(
              padding: const EdgeInsets.only(top: 8, bottom: 4),
              child: Container(width: 60, height: 4, color: border),
            ),
            // 헤더
            const _OptionsHeader(),
            // 메뉴 목록
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(12),
                child: _OptionsMenuBody(config: config),
              ),
            ),
          ],
        ),
      ),
    ),
  );
}

class _OptionsHeader extends StatelessWidget {
  const _OptionsHeader();

  @override
  Widget build(BuildContext context) {
    final gold = RetroColors.goldOf(context);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      width: double.infinity,
      decoration: BoxDecoration(
        color: RetroColors.panelBgOf(context),
        border: Border(bottom: BorderSide(color: gold, width: 2)),
      ),
      child: Row(
        children: [
          Icon(Icons.settings, color: gold, size: 18),
          const SizedBox(width: 8),
          Text(
            L10n.of(context).optionsTitle,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: gold,
            ),
          ),
          const Spacer(),
          RetroIconButton(
            icon: Icons.close,
            onPressed: () => Navigator.pop(context),
            size: 28,
          ),
        ],
      ),
    );
  }
}

class _OptionsMenuBody extends StatelessWidget {
  const _OptionsMenuBody({required this.config});

  final MobileOptionsConfig config;

  @override
  Widget build(BuildContext context) {
    final gold = RetroColors.goldOf(context);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // === 게임 제어 ===
        RetroMenuSection(title: L10n.of(context).controlSection),
        const SizedBox(height: 8),
        _buildPauseItem(context),
        const SizedBox(height: 8),
        RetroMenuItem(
          icon: Icons.speed,
          iconColor: gold,
          label: l10n.menuSpeed.toUpperCase(),
          trailing: _buildSpeedSelector(context),
        ),
        const SizedBox(height: 16),

        // === 정보 ===
        RetroMenuSection(title: L10n.of(context).infoSection),
        const SizedBox(height: 8),
        if (config.onShowStatistics != null)
          RetroMenuItem(
            icon: Icons.bar_chart,
            iconColor: RetroColors.mpOf(context),
            label: l10n.uiStatistics.toUpperCase(),
            onTap: () {
              Navigator.pop(context);
              config.onShowStatistics?.call();
            },
          ),
        if (config.onShowHelp != null) ...[
          const SizedBox(height: 8),
          RetroMenuItem(
            icon: Icons.help_outline,
            iconColor: RetroColors.expOf(context),
            label: l10n.uiHelp.toUpperCase(),
            onTap: () {
              Navigator.pop(context);
              config.onShowHelp?.call();
            },
          ),
        ],
        const SizedBox(height: 16),

        // === 설정 ===
        RetroMenuSection(title: L10n.of(context).settingsSection),
        const SizedBox(height: 8),
        _buildLanguageItem(context),
        if (config.onBgmVolumeChange != null ||
            config.onSfxVolumeChange != null) ...[
          const SizedBox(height: 8),
          _buildSoundItem(context),
        ],
        const SizedBox(height: 16),

        // === 저장/종료 ===
        RetroMenuSection(title: L10n.of(context).saveExitSection),
        const SizedBox(height: 8),
        _buildSaveItem(context),
        const SizedBox(height: 8),
        _buildNewGameItem(context),
        const SizedBox(height: 8),
        _buildExitItem(context),

        // === 치트 섹션 ===
        if (config.cheatsEnabled) ...[
          const SizedBox(height: 16),
          _buildCheatSection(context),
        ],

        // === 디버그 도구 섹션 ===
        if (kDebugMode && config.onCreateTestCharacter != null) ...[
          const SizedBox(height: 16),
          _buildDebugSection(context),
        ],
        const SizedBox(height: 16),
      ],
    );
  }

  Widget _buildPauseItem(BuildContext context) {
    return RetroMenuItem(
      icon: config.isPaused ? Icons.play_arrow : Icons.pause,
      iconColor: config.isPaused
          ? RetroColors.expOf(context)
          : RetroColors.warningOf(context),
      label: config.isPaused
          ? l10n.menuResume.toUpperCase()
          : l10n.menuPause.toUpperCase(),
      onTap: () {
        Navigator.pop(context);
        config.onPauseToggle();
      },
    );
  }

  Widget _buildSpeedSelector(BuildContext context) {
    return RetroSpeedChip(
      speed: config.adSpeedMultiplier,
      isSelected: config.isSpeedBoostActive,
      isAdBased: !config.isSpeedBoostActive && !config.isPaidUser,
      isDisabled: config.isSpeedBoostActive,
      onTap: () {
        if (!config.isSpeedBoostActive) {
          config.onSpeedBoostActivate?.call();
        }
        Navigator.pop(context);
      },
    );
  }

  Widget _buildLanguageItem(BuildContext context) {
    final currentLang = _getCurrentLanguageName();
    return RetroMenuItem(
      icon: Icons.language,
      iconColor: RetroColors.mpOf(context),
      label: l10n.menuLanguage.toUpperCase(),
      value: currentLang,
      onTap: () {
        Navigator.pop(context);
        _showLanguageDialog(context);
      },
    );
  }

  Widget _buildSoundItem(BuildContext context) {
    final bgmPercent = (config.bgmVolume * 100).round();
    final sfxPercent = (config.sfxVolume * 100).round();
    final status = (bgmPercent == 0 && sfxPercent == 0)
        ? l10n.uiSoundOff
        : 'BGM $bgmPercent% / SFX $sfxPercent%';

    return RetroMenuItem(
      icon: config.bgmVolume == 0 && config.sfxVolume == 0
          ? Icons.volume_off
          : Icons.volume_up,
      iconColor: RetroColors.textMutedOf(context),
      label: l10n.uiSound.toUpperCase(),
      value: status,
      onTap: () {
        Navigator.pop(context);
        _showSoundDialog(context);
      },
    );
  }

  Widget _buildSaveItem(BuildContext context) {
    return RetroMenuItem(
      icon: Icons.save,
      iconColor: RetroColors.mpOf(context),
      label: l10n.menuSave.toUpperCase(),
      onTap: () {
        Navigator.pop(context);
        config.onSave();
        config.notificationService.showGameSaved(l10n.menuSaved);
      },
    );
  }

  Widget _buildNewGameItem(BuildContext context) {
    return RetroMenuItem(
      icon: Icons.refresh,
      iconColor: RetroColors.warningOf(context),
      label: l10n.menuNewGame.toUpperCase(),
      subtitle: l10n.menuDeleteSave,
      onTap: () {
        Navigator.pop(context);
        _showDeleteConfirmDialog(context);
      },
    );
  }

  Widget _buildExitItem(BuildContext context) {
    return RetroMenuItem(
      icon: Icons.exit_to_app,
      iconColor: RetroColors.hpOf(context),
      label: L10n.of(context).exitGame.toUpperCase(),
      onTap: () {
        Navigator.pop(context);
        config.onExit();
      },
    );
  }

  Widget _buildCheatSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RetroMenuSection(
          title: L10n.of(context).debugCheatsTitle,
          color: RetroColors.hpOf(context),
        ),
        const SizedBox(height: 8),
        RetroMenuItem(
          icon: Icons.fast_forward,
          iconColor: RetroColors.hpOf(context),
          label: L10n.of(context).debugSkipTask,
          subtitle: L10n.of(context).debugSkipTaskDesc,
          onTap: () {
            Navigator.pop(context);
            config.onCheatTask?.call();
          },
        ),
        const SizedBox(height: 8),
        RetroMenuItem(
          icon: Icons.skip_next,
          iconColor: RetroColors.hpOf(context),
          label: L10n.of(context).debugSkipQuest,
          subtitle: L10n.of(context).debugSkipQuestDesc,
          onTap: () {
            Navigator.pop(context);
            config.onCheatQuest?.call();
          },
        ),
        const SizedBox(height: 8),
        RetroMenuItem(
          icon: Icons.double_arrow,
          iconColor: RetroColors.hpOf(context),
          label: L10n.of(context).debugSkipAct,
          subtitle: L10n.of(context).debugSkipActDesc,
          onTap: () {
            Navigator.pop(context);
            config.onCheatPlot?.call();
          },
        ),
      ],
    );
  }

  Widget _buildDebugSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RetroMenuSection(
          title: L10n.of(context).debugToolsTitle,
          color: RetroColors.warningOf(context),
        ),
        const SizedBox(height: 8),
        RetroMenuItem(
          icon: Icons.science,
          iconColor: RetroColors.warningOf(context),
          label: L10n.of(context).debugCreateTestCharacter,
          subtitle: L10n.of(context).debugCreateTestCharacterDesc,
          onTap: () {
            Navigator.pop(context);
            _showTestCharacterDialog(context);
          },
        ),
      ],
    );
  }

  String _getCurrentLanguageName() {
    final locale = l10n.currentGameLocale;
    if (locale == 'ko') return l10n.languageKorean;
    if (locale == 'ja') return l10n.languageJapanese;
    return l10n.languageEnglish;
  }

  void _showLanguageDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (context) => RetroSelectDialog(
        title: l10n.menuLanguage.toUpperCase(),
        children: [
          _buildLangOption(
            context,
            'en',
            l10n.languageEnglish,
            '\u{1F1FA}\u{1F1F8}',
          ),
          _buildLangOption(
            context,
            'ko',
            l10n.languageKorean,
            '\u{1F1F0}\u{1F1F7}',
          ),
          _buildLangOption(
            context,
            'ja',
            l10n.languageJapanese,
            '\u{1F1EF}\u{1F1F5}',
          ),
        ],
      ),
    );
  }

  Widget _buildLangOption(
    BuildContext context,
    String locale,
    String label,
    String flag,
  ) {
    final isSelected = l10n.currentGameLocale == locale;
    return RetroOptionItem(
      label: label.toUpperCase(),
      prefix: flag,
      isSelected: isSelected,
      onTap: () {
        Navigator.pop(context);
        config.onLanguageChange(locale);
      },
    );
  }

  void _showSoundDialog(BuildContext context) {
    var bgmVolume = config.bgmVolume;
    var sfxVolume = config.sfxVolume;

    showDialog<void>(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => RetroSoundDialog(
          bgmVolume: bgmVolume,
          sfxVolume: sfxVolume,
          onBgmChanged: (double value) {
            setDialogState(() => bgmVolume = value);
            config.onBgmVolumeChange?.call(value);
          },
          onSfxChanged: (double value) {
            setDialogState(() => sfxVolume = value);
            config.onSfxVolumeChange?.call(value);
          },
        ),
      ),
    );
  }

  void _showDeleteConfirmDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (context) => RetroConfirmDialog(
        title: l10n.confirmDeleteTitle.toUpperCase(),
        message: l10n.confirmDeleteMessage,
        confirmText: l10n.buttonConfirm.toUpperCase(),
        cancelText: l10n.buttonCancel.toUpperCase(),
        onConfirm: () {
          Navigator.pop(context);
          config.onDeleteSaveAndNewGame();
        },
        onCancel: () => Navigator.pop(context),
      ),
    );
  }

  void _showTestCharacterDialog(BuildContext context) {
    showDialog<bool>(
      context: context,
      builder: (context) => RetroConfirmDialog(
        title: L10n.of(context).debugCreateTestCharacterTitle,
        message: L10n.of(context).debugCreateTestCharacterMessage,
        confirmText: L10n.of(context).createButton,
        cancelText: L10n.of(context).cancel.toUpperCase(),
        onConfirm: () {
          Navigator.of(context).pop(true);
          config.onCreateTestCharacter?.call();
        },
        onCancel: () => Navigator.of(context).pop(false),
      ),
    );
  }
}
