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

import 'package:asciineverdie/data/game_text_l10n.dart' as game_l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/engine/debug_settings_service.dart';
import 'package:asciineverdie/src/core/storage/settings_repository.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_widgets.dart';
import 'package:asciineverdie/src/features/settings/retro_settings_widgets.dart';

/// 통합 설정 화면 (레트로 스타일)
class SettingsScreen extends StatefulWidget {
  const SettingsScreen({
    super.key,
    required this.settingsRepository,
    this.onLocaleChange,
    this.onBgmVolumeChange,
    this.onSfxVolumeChange,
    this.onCreateTestCharacter,
  });

  final SettingsRepository settingsRepository;
  final void Function(String locale)? onLocaleChange;
  final void Function(double volume)? onBgmVolumeChange;
  final void Function(double volume)? onSfxVolumeChange;
  final Future<void> Function()? onCreateTestCharacter;

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();

  /// 설정 화면을 모달 바텀시트로 표시
  static Future<void> show(
    BuildContext context, {
    required SettingsRepository settingsRepository,
    void Function(String locale)? onLocaleChange,
    void Function(double volume)? onBgmVolumeChange,
    void Function(double volume)? onSfxVolumeChange,
    Future<void> Function()? onCreateTestCharacter,
  }) {
    return showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      backgroundColor: Colors.transparent,
      builder: (context) => DraggableScrollableSheet(
        initialChildSize: 0.7,
        minChildSize: 0.5,
        maxChildSize: 0.95,
        expand: false,
        builder: (context, scrollController) => SettingsScreen(
          settingsRepository: settingsRepository,
          onLocaleChange: onLocaleChange,
          onBgmVolumeChange: onBgmVolumeChange,
          onSfxVolumeChange: onSfxVolumeChange,
          onCreateTestCharacter: onCreateTestCharacter,
        ),
      ),
    );
  }
}

class _SettingsScreenState extends State<SettingsScreen> {
  double _bgmVolume = 0.7;
  double _sfxVolume = 0.8;
  bool _isLoading = true;

  // 디버그 설정 상태 (Phase 8)
  bool _debugIapSimulated = false;
  int _debugOfflineHours = 0;

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    final bgm = await widget.settingsRepository.loadBgmVolume();
    final sfx = await widget.settingsRepository.loadSfxVolume();

    // 디버그 설정 로드 (Phase 8)
    final debugSettings = DebugSettingsService.instance;
    final iapSimulated = debugSettings.iapSimulated;
    final offlineHours = debugSettings.offlineHours;

    if (mounted) {
      setState(() {
        _bgmVolume = bgm;
        _sfxVolume = sfx;
        _debugIapSimulated = iapSimulated;
        _debugOfflineHours = offlineHours;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Container(
        decoration: BoxDecoration(
          color: RetroColors.backgroundOf(context),
          borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
        ),
        child: Center(
          child: Text(
            'LOADING...',
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 12,
              color: RetroColors.goldOf(context),
            ),
          ),
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: RetroColors.backgroundOf(context),
        borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
        border: Border.all(color: RetroColors.borderOf(context), width: 2),
      ),
      child: Column(
        children: [
          // 핸들 바 (레트로 스타일)
          _buildHandle(context),
          // 헤더
          _buildHeader(context),
          // 설정 목록
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(12),
              children: [
                // 언어 설정
                RetroSectionTitle(title: game_l10n.uiLanguage),
                const SizedBox(height: 8),
                _buildLanguageSelector(context),
                const SizedBox(height: 16),

                // 사운드 설정
                RetroSectionTitle(title: game_l10n.uiSound),
                const SizedBox(height: 8),
                _buildSoundSettings(context),

                // 디버그 섹션 (디버그 모드에서만 표시)
                if (kDebugMode) ...[
                  const SizedBox(height: 16),
                  RetroSectionTitle(title: L10n.of(context).debugTitle),
                  const SizedBox(height: 8),
                  _buildDebugSection(context),
                ],
                const SizedBox(height: 24),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHandle(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 4),
      child: Container(
        width: 60,
        height: 4,
        decoration: BoxDecoration(
          color: RetroColors.borderOf(context),
          border: Border.all(
            color: RetroColors.borderLightOf(context),
            width: 1,
          ),
        ),
      ),
    );
  }

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

  Widget _buildLanguageSelector(BuildContext context) {
    final currentLocale = game_l10n.currentGameLocale;
    final languages = [
      ('en', 'ENGLISH', '🇺🇸'),
      ('ko', '한국어', '🇰🇷'),
      ('ja', '日本語', '🇯🇵'),
    ];

    return RetroPanel(
      padding: const EdgeInsets.all(8),
      child: Column(
        children: languages.map((lang) {
          final isSelected = currentLocale == lang.$1;
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 2),
            child: RetroSelectableItem(
              isSelected: isSelected,
              onTap: () {
                game_l10n.setGameLocale(lang.$1);
                widget.settingsRepository.saveLocale(lang.$1);
                widget.onLocaleChange?.call(lang.$1);
                setState(() {});
              },
              child: Row(
                children: [
                  Text(lang.$3, style: const TextStyle(fontSize: 16)),
                  const SizedBox(width: 12),
                  Text(
                    lang.$2,
                    style: TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 10,
                      color: isSelected
                          ? RetroColors.goldOf(context)
                          : RetroColors.textPrimaryOf(context),
                    ),
                  ),
                  const Spacer(),
                  if (isSelected)
                    Icon(
                      Icons.check,
                      size: 16,
                      color: RetroColors.goldOf(context),
                    ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildSoundSettings(BuildContext context) {
    return RetroPanel(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          RetroVolumeSlider(
            label: game_l10n.uiBgmVolume,
            icon: Icons.music_note,
            value: _bgmVolume,
            onChanged: (value) {
              setState(() => _bgmVolume = value);
              widget.settingsRepository.saveBgmVolume(value);
              widget.onBgmVolumeChange?.call(value);
            },
          ),
          const SizedBox(height: 12),
          RetroVolumeSlider(
            label: game_l10n.uiSfxVolume,
            icon: Icons.volume_up,
            value: _sfxVolume,
            onChanged: (value) {
              setState(() => _sfxVolume = value);
              widget.settingsRepository.saveSfxVolume(value);
              widget.onSfxVolumeChange?.call(value);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildDebugSection(BuildContext context) {
    return RetroPanel(
      padding: const EdgeInsets.all(12),
      backgroundColor: RetroColors.hpOf(context).withValues(alpha: 0.1),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 헤더
          Row(
            children: [
              Icon(
                Icons.bug_report,
                color: RetroColors.hpOf(context),
                size: 16,
              ),
              const SizedBox(width: 8),
              Text(
                L10n.of(context).debugDeveloperTools,
                style: TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 10,
                  color: RetroColors.hpOf(context),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // IAP 시뮬레이션 토글
          RetroDebugToggle(
            icon: Icons.shopping_cart,
            label: L10n.of(context).debugIapPurchased,
            description: L10n.of(context).debugIapPurchasedDesc,
            value: _debugIapSimulated,
            onChanged: (value) async {
              await DebugSettingsService.instance.setIapSimulated(value);
              setState(() => _debugIapSimulated = value);
            },
          ),
          const SizedBox(height: 12),

          // 오프라인 시간 시뮬레이션
          _buildOfflineHoursSelector(context),
          const SizedBox(height: 16),

          // 구분선
          Container(
            height: 1,
            color: RetroColors.hpOf(context).withValues(alpha: 0.3),
          ),
          const SizedBox(height: 12),

          // 테스트 캐릭터 생성
          if (widget.onCreateTestCharacter != null) ...[
            Text(
              L10n.of(context).debugTestCharacterDesc,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 7,
                color: RetroColors.textMutedOf(context),
                height: 1.6,
              ),
            ),
            const SizedBox(height: 12),
            SizedBox(
              width: double.infinity,
              child: RetroTextButton(
                text: L10n.of(context).debugCreateTestCharacter,
                icon: Icons.science,
                onPressed: _handleCreateTestCharacter,
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildOfflineHoursSelector(BuildContext context) {
    final options = DebugSettingsService.offlineHoursOptions;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(
              Icons.timer,
              size: 14,
              color: RetroColors.textPrimaryOf(context),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    L10n.of(context).debugOfflineHours,
                    style: TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 8,
                      color: RetroColors.textPrimaryOf(context),
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    L10n.of(context).debugOfflineHoursDesc,
                    style: TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 6,
                      color: RetroColors.textMutedOf(context),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 6,
          runSpacing: 6,
          children: options.map((hours) {
            final isSelected = _debugOfflineHours == hours;
            final label = hours == 0 ? 'OFF' : '${hours}H';

            return RetroChip(
              label: label,
              isSelected: isSelected,
              onTap: () async {
                await DebugSettingsService.instance.setOfflineHours(hours);
                setState(() => _debugOfflineHours = hours);
              },
            );
          }).toList(),
        ),
      ],
    );
  }

  Future<void> _handleCreateTestCharacter() async {
    final confirmed = await 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(),
      ),
    );

    if (confirmed == true && mounted) {
      await widget.onCreateTestCharacter?.call();
      if (mounted) {
        Navigator.of(context).pop();
      }
    }
  }
}
