import 'dart:io' show Platform;

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

import 'package:asciineverdie/data/game_text_l10n.dart' as game_l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/app.dart' show SavedGamePreview;
import 'package:asciineverdie/src/features/front/widgets/hero_vs_boss_animation.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_widgets.dart';

class FrontScreen extends StatefulWidget {
  const FrontScreen({
    super.key,
    this.onNewCharacter,
    this.onLoadSave,
    this.onHallOfFame,
    this.onLocalArena,
    this.onSettings,
    this.onPurchaseRemoveAds,
    this.onRestorePurchase,
    this.hasSaveFile = false,
    this.savedGamePreview,
    this.hallOfFameCount = 0,
    this.isAdRemovalPurchased = false,
    this.removeAdsPrice,
    this.routeObserver,
    this.onRefresh,
  });

  /// "New character" 버튼 클릭 시 호출
  final void Function(BuildContext context)? onNewCharacter;

  /// "Load save" 버튼 클릭 시 호출
  final Future<void> Function(BuildContext context)? onLoadSave;

  /// "Hall of Fame" 버튼 클릭 시 호출
  final void Function(BuildContext context)? onHallOfFame;

  /// "Local Arena" 버튼 클릭 시 호출
  final void Function(BuildContext context)? onLocalArena;

  /// "Settings" 버튼 클릭 시 호출 (언어, 테마, 사운드)
  final void Function(BuildContext context)? onSettings;

  /// "광고 제거" 구매 버튼 클릭 시 호출
  final Future<void> Function(BuildContext context)? onPurchaseRemoveAds;

  /// "구매 복원" 버튼 클릭 시 호출
  final Future<void> Function(BuildContext context)? onRestorePurchase;

  /// 세이브 파일 존재 여부 (새 캐릭터 시 경고용)
  final bool hasSaveFile;

  /// 저장된 게임 미리보기 정보
  final SavedGamePreview? savedGamePreview;

  /// 명예의 전당 캐릭터 수 (아레나 활성화 조건: 2명 이상)
  final int hallOfFameCount;

  /// 광고 제거 구매 여부
  final bool isAdRemovalPurchased;

  /// 광고 제거 상품 가격 (null이면 스토어 비활성)
  final String? removeAdsPrice;

  /// RouteObserver (화면 복귀 시 갱신용)
  final RouteObserver<ModalRoute<void>>? routeObserver;

  /// 화면 복귀 시 호출할 콜백
  final VoidCallback? onRefresh;

  @override
  State<FrontScreen> createState() => _FrontScreenState();
}

class _FrontScreenState extends State<FrontScreen> with RouteAware {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // RouteObserver 구독
    final route = ModalRoute.of(context);
    if (route != null) {
      widget.routeObserver?.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    widget.routeObserver?.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    // 다른 화면에서 돌아왔을 때 갱신
    widget.onRefresh?.call();
  }

  /// 새 캐릭터 생성 시 세이브 파일 존재하면 경고 표시
  void _handleNewCharacter(BuildContext context) {
    if (widget.hasSaveFile) {
      _showDeleteWarningDialog(context);
    } else {
      widget.onNewCharacter?.call(context);
    }
  }

  /// 세이브 삭제 경고 다이얼로그
  void _showDeleteWarningDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: Text(game_l10n.uiWarning),
        content: Text(game_l10n.warningDeleteSave),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(dialogContext),
            child: Text(game_l10n.buttonCancel),
          ),
          FilledButton(
            onPressed: () {
              Navigator.pop(dialogContext);
              widget.onNewCharacter?.call(context);
            },
            child: Text(game_l10n.buttonConfirm),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: RetroColors.deepBrown,
      body: SafeArea(
        child: Column(
          children: [
            // 스크롤 영역 (헤더, 애니메이션, 버튼)
            Expanded(
              child: Center(
                child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 800),
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        const _AnimationPanel(),
                        const SizedBox(height: 16),
                        _ActionButtons(
                          onNewCharacter: widget.onNewCharacter != null
                              ? () => _handleNewCharacter(context)
                              : null,
                          onLoadSave: widget.onLoadSave != null
                              ? () => widget.onLoadSave!(context)
                              : null,
                          onHallOfFame: widget.onHallOfFame != null
                              ? () => widget.onHallOfFame!(context)
                              : null,
                          onLocalArena:
                              widget.onLocalArena != null &&
                                  widget.hallOfFameCount >= 2
                              ? () => widget.onLocalArena!(context)
                              : null,
                          onSettings: widget.onSettings != null
                              ? () => widget.onSettings!(context)
                              : null,
                          onPurchaseRemoveAds:
                              widget.onPurchaseRemoveAds != null
                              ? () => widget.onPurchaseRemoveAds!(context)
                              : null,
                          onRestorePurchase: widget.onRestorePurchase != null
                              ? () => widget.onRestorePurchase!(context)
                              : null,
                          savedGamePreview: widget.savedGamePreview,
                          hallOfFameCount: widget.hallOfFameCount,
                          isAdRemovalPurchased: widget.isAdRemovalPurchased,
                          removeAdsPrice: widget.removeAdsPrice,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            // 카피라이트 푸터 (하단 고정)
            const _CopyrightFooter(),
          ],
        ),
      ),
    );
  }
}

/// 애니메이션 패널 (금색 테두리 + 아이콘+타이틀)
class _AnimationPanel extends StatelessWidget {
  const _AnimationPanel();

  /// 플랫폼별 비율 반환 (데스크톱: 넓게, 모바일: 높게)
  double _getAspectRatio() {
    if (kIsWeb) return 2.5; // 웹: 넓은 비율
    if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
      return 2.5; // 데스크톱: 넓은 비율
    }
    return 16 / 9; // 모바일(iOS/Android): 16:9
  }

  @override
  Widget build(BuildContext context) {
    return RetroGoldPanel(
      titleWidget: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.auto_awesome, color: RetroColors.gold, size: 18),
          const SizedBox(width: 10),
          Text(
            L10n.of(context).appTitle.toUpperCase(),
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: RetroColors.gold,
              shadows: [
                Shadow(color: RetroColors.goldDark, offset: Offset(2, 2)),
              ],
            ),
          ),
        ],
      ),
      padding: const EdgeInsets.all(8),
      child: AspectRatio(
        aspectRatio: _getAspectRatio(),
        child: const HeroVsBossAnimation(),
      ),
    );
  }
}

/// 액션 버튼 (레트로 스타일)
class _ActionButtons extends StatelessWidget {
  const _ActionButtons({
    this.onNewCharacter,
    this.onLoadSave,
    this.onHallOfFame,
    this.onLocalArena,
    this.onSettings,
    this.onPurchaseRemoveAds,
    this.onRestorePurchase,
    this.savedGamePreview,
    this.hallOfFameCount = 0,
    this.isAdRemovalPurchased = false,
    this.removeAdsPrice,
  });

  final VoidCallback? onNewCharacter;
  final VoidCallback? onLoadSave;
  final VoidCallback? onHallOfFame;
  final VoidCallback? onLocalArena;
  final VoidCallback? onSettings;
  final VoidCallback? onPurchaseRemoveAds;
  final VoidCallback? onRestorePurchase;
  final SavedGamePreview? savedGamePreview;
  final int hallOfFameCount;
  final bool isAdRemovalPurchased;
  final String? removeAdsPrice;

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);

    return RetroPanel(
      title: L10n.of(context).menuTitle,
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 새 캐릭터 (Primary)
          RetroTextButton(
            text: l10n.newCharacter,
            icon: Icons.casino_outlined,
            onPressed: onNewCharacter,
          ),
          const SizedBox(height: 12),
          // 불러오기 (Secondary)
          RetroTextButton(
            text: l10n.loadSave,
            icon: Icons.folder_open,
            onPressed: onLoadSave,
            isPrimary: false,
          ),
          // 저장된 게임 정보 표시
          if (savedGamePreview != null) ...[
            const SizedBox(height: 6),
            _SavedGameInfo(preview: savedGamePreview!),
          ],
          const SizedBox(height: 12),
          // 명예의 전당
          if (onHallOfFame != null)
            RetroTextButton(
              text: game_l10n.uiHallOfFame,
              icon: Icons.emoji_events_outlined,
              onPressed: onHallOfFame,
              isPrimary: false,
            ),
          // 로컬 아레나 (항상 표시, 2명 이상일 때만 활성화)
          const SizedBox(height: 12),
          RetroTextButton(
            text: game_l10n.uiLocalArena,
            icon: Icons.sports_kabaddi,
            onPressed: hallOfFameCount >= 2 ? onLocalArena : null,
            isPrimary: false,
          ),
          // 설정
          const SizedBox(height: 12),
          RetroTextButton(
            text: game_l10n.uiSettings,
            icon: Icons.settings,
            onPressed: onSettings,
            isPrimary: false,
          ),
          // IAP 구매 (광고 제거) - 스토어 사용 가능할 때 표시 (구매 완료 시 비활성화)
          if (removeAdsPrice != null) ...[
            const SizedBox(height: 20),
            const Divider(color: RetroColors.panelBorderInner, height: 1),
            const SizedBox(height: 12),
            _IapPurchaseButton(
              price: removeAdsPrice!,
              onPurchase: onPurchaseRemoveAds,
              onRestore: onRestorePurchase,
              enabled: !isAdRemovalPurchased,
            ),
          ],
          // 이미 구매된 경우 배지 표시
          if (isAdRemovalPurchased) ...[
            const SizedBox(height: 8),
            _PurchasedBadge(),
          ],
        ],
      ),
    );
  }
}

/// 저장된 게임 미리보기 정보 위젯
class _SavedGameInfo extends StatelessWidget {
  const _SavedGameInfo({required this.preview});

  final SavedGamePreview preview;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.person_outline,
            size: 10,
            color: RetroColors.textDisabled,
          ),
          const SizedBox(width: 4),
          Text(
            '${preview.characterName}  Lv.${preview.level}  ${preview.actName}',
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 11,
              color: RetroColors.textDisabled,
            ),
          ),
        ],
      ),
    );
  }
}

/// 카피라이트 푸터
class _CopyrightFooter extends StatelessWidget {
  const _CopyrightFooter();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: FutureBuilder<PackageInfo>(
        future: PackageInfo.fromPlatform(),
        builder: (context, snapshot) {
          final version = snapshot.data?.version ?? '';
          final versionSuffix = version.isNotEmpty ? ' v$version' : '';
          return Text(
            '${game_l10n.copyrightText}$versionSuffix',
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 7,
              color: RetroColors.textDisabled,
            ),
          );
        },
      ),
    );
  }
}

/// IAP 구매 버튼 (광고 제거)
class _IapPurchaseButton extends StatelessWidget {
  const _IapPurchaseButton({
    required this.price,
    this.onPurchase,
    this.onRestore,
    this.enabled = true,
  });

  final String price;
  final VoidCallback? onPurchase;
  final VoidCallback? onRestore;
  final bool enabled;

  void _showPurchaseDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (dialogContext) => _IapPurchaseDialog(
        price: price,
        onPurchase: () {
          Navigator.pop(dialogContext);
          onPurchase?.call();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 비활성화 상태의 색상
    final buttonColor = enabled ? RetroColors.gold : RetroColors.textDisabled;
    final bgGradient = enabled
        ? const LinearGradient(
            colors: [Color(0xFF4A3B2A), Color(0xFF3D2E1F)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          )
        : const LinearGradient(
            colors: [Color(0xFF3A3A3A), Color(0xFF2A2A2A)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 구매 버튼 (클릭 시 팝업)
        Container(
          decoration: BoxDecoration(
            gradient: bgGradient,
            border: Border.all(color: buttonColor, width: 2),
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: enabled ? () => _showPurchaseDialog(context) : null,
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
                child: Row(
                  children: [
                    Icon(Icons.block, color: buttonColor, size: 24),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            game_l10n.iapRemoveAds,
                            style: TextStyle(
                              fontFamily: 'PressStart2P',
                              fontSize: 12,
                              color: buttonColor,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            game_l10n.iapRemoveAdsDesc,
                            style: const TextStyle(
                              fontFamily: 'PressStart2P',
                              fontSize: 9,
                              color: RetroColors.textDisabled,
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 화살표 아이콘 (상세 보기)
                    Icon(Icons.arrow_forward_ios, color: buttonColor, size: 16),
                  ],
                ),
              ),
            ),
          ),
        ),
        const SizedBox(height: 8),
        // 복원 버튼
        Center(
          child: TextButton(
            onPressed: enabled ? onRestore : null,
            child: Text(
              game_l10n.iapRestorePurchase,
              style: const TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 9,
                color: RetroColors.textDisabled,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

/// IAP 구매 팝업 다이얼로그
class _IapPurchaseDialog extends StatelessWidget {
  const _IapPurchaseDialog({required this.price, this.onPurchase});

  final String price;
  final VoidCallback? onPurchase;

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: RetroColors.deepBrown,
      shape: RoundedRectangleBorder(
        side: const BorderSide(color: RetroColors.gold, width: 2),
        borderRadius: BorderRadius.circular(4),
      ),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 360),
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 타이틀
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.star, color: RetroColors.gold, size: 20),
                  const SizedBox(width: 8),
                  Text(
                    game_l10n.iapBenefitTitle,
                    style: const TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 12,
                      color: RetroColors.gold,
                    ),
                  ),
                  const SizedBox(width: 8),
                  const Icon(Icons.star, color: RetroColors.gold, size: 20),
                ],
              ),
              const SizedBox(height: 20),
              // 혜택 목록
              _BenefitItem(icon: Icons.block, text: game_l10n.iapBenefit1),
              const SizedBox(height: 8),
              _BenefitItem(icon: Icons.flash_on, text: game_l10n.iapBenefit2),
              const SizedBox(height: 8),
              _BenefitItem(icon: Icons.undo, text: game_l10n.iapBenefit3),
              const SizedBox(height: 8),
              _BenefitItem(icon: Icons.casino, text: game_l10n.iapBenefit4),
              const SizedBox(height: 8),
              _BenefitItem(icon: Icons.speed, text: game_l10n.iapBenefit5),
              const SizedBox(height: 8),
              _BenefitItem(
                icon: Icons.inventory_2,
                text: game_l10n.iapBenefit6,
              ),
              const SizedBox(height: 20),
              // 가격 + 구매 버튼
              Container(
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFF5A4B3A), Color(0xFF4A3B2A)],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                  border: Border.all(color: RetroColors.gold, width: 2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: onPurchase,
                    borderRadius: BorderRadius.circular(2),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            game_l10n.iapPurchaseButton,
                            style: const TextStyle(
                              fontFamily: 'PressStart2P',
                              fontSize: 12,
                              color: RetroColors.gold,
                            ),
                          ),
                          const SizedBox(width: 12),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: RetroColors.gold,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              price,
                              style: const TextStyle(
                                fontFamily: 'PressStart2P',
                                fontSize: 11,
                                color: RetroColors.deepBrown,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 12),
              // 취소 버튼
              Center(
                child: TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    game_l10n.buttonCancel,
                    style: const TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 10,
                      color: RetroColors.textDisabled,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 혜택 항목 위젯
class _BenefitItem extends StatelessWidget {
  const _BenefitItem({required this.icon, required this.text});

  final IconData icon;
  final String text;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, color: RetroColors.expGreen, size: 18),
        const SizedBox(width: 12),
        Expanded(
          child: Text(
            text,
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 10,
              color: RetroColors.textLight,
            ),
          ),
        ),
      ],
    );
  }
}

/// 이미 구매됨 뱃지
class _PurchasedBadge extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: RetroColors.panelBgLight,
        border: Border.all(color: RetroColors.expGreen, width: 2),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.check_circle, color: RetroColors.expGreen, size: 20),
          const SizedBox(width: 8),
          Text(
            game_l10n.iapAlreadyPurchased,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 11,
              color: RetroColors.expGreen,
            ),
          ),
        ],
      ),
    );
  }
}
