import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/data/potion_data.dart';
import 'package:asciineverdie/src/core/engine/iap_service.dart';
import 'package:asciineverdie/src/core/engine/return_rewards_service.dart';
import 'package:asciineverdie/src/core/model/item_stats.dart';
import 'package:asciineverdie/src/core/model/treasure_chest.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 복귀 보상 다이얼로그 (Phase 7)
///
/// 게임 복귀 시 보물 상자 보상을 표시하는 다이얼로그
class ReturnRewardsDialog extends StatefulWidget {
  const ReturnRewardsDialog({
    super.key,
    required this.reward,
    required this.playerLevel,
    required this.onClaim,
  });

  /// 복귀 보상 데이터
  final ReturnChestReward reward;

  /// 플레이어 레벨 (상자 보상 스케일링용)
  final int playerLevel;

  /// 보상 수령 콜백 (상자 보상 목록)
  final void Function(List<ChestReward> rewards) onClaim;

  /// 다이얼로그 표시
  static Future<void> show(
    BuildContext context, {
    required ReturnChestReward reward,
    required int playerLevel,
    required void Function(List<ChestReward> rewards) onClaim,
  }) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (context) => ReturnRewardsDialog(
        reward: reward,
        playerLevel: playerLevel,
        onClaim: onClaim,
      ),
    );
  }

  @override
  State<ReturnRewardsDialog> createState() => _ReturnRewardsDialogState();
}

class _ReturnRewardsDialogState extends State<ReturnRewardsDialog>
    with SingleTickerProviderStateMixin {
  final _rewardsService = ReturnRewardsService.instance;

  // 상태
  bool _basicOpened = false;
  bool _bonusOpened = false;
  bool _isOpeningBasic = false;
  bool _isOpeningBonus = false;
  List<ChestReward> _basicRewards = [];
  List<ChestReward> _bonusRewards = [];

  // 애니메이션
  late AnimationController _animController;
  late Animation<double> _shakeAnimation;

  @override
  void initState() {
    super.initState();
    _animController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    _shakeAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animController, curve: Curves.elasticOut),
    );
  }

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

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

    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: const BoxConstraints(maxWidth: 400),
        decoration: BoxDecoration(
          color: panelBg,
          border: Border(
            top: BorderSide(color: gold, width: 4),
            left: BorderSide(color: gold, width: 4),
            bottom: BorderSide(color: borderColor, width: 4),
            right: BorderSide(color: borderColor, width: 4),
          ),
          boxShadow: [
            BoxShadow(
              color: gold.withValues(alpha: 0.4),
              blurRadius: 20,
              spreadRadius: 2,
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 헤더
            _buildHeader(context, gold),

            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 떠나있던 시간
                  Text(
                    l10n.returnRewardHoursAway(
                      _rewardsService.formatHoursAway(widget.reward.hoursAway),
                    ),
                    style: TextStyle(
                      fontFamily: 'PressStart2P',
                      fontSize: 10,
                      color: gold.withValues(alpha: 0.8),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 20),

                  // 기본 상자 섹션
                  _buildChestSection(
                    context,
                    title: l10n.returnRewardChests(widget.reward.chestCount),
                    chestCount: widget.reward.chestCount,
                    rewards: _basicRewards,
                    isOpened: _basicOpened,
                    isOpening: _isOpeningBasic,
                    onOpen: _openBasicChests,
                    isGold: true,
                  ),

                  const SizedBox(height: 16),

                  // 보너스 상자 섹션
                  _buildChestSection(
                    context,
                    title: l10n.returnRewardBonusChests,
                    chestCount: widget.reward.bonusChestCount,
                    rewards: _bonusRewards,
                    isOpened: _bonusOpened,
                    isOpening: _isOpeningBonus,
                    onOpen: _openBonusChests,
                    isGold: false,
                    enabled: _basicOpened && !_bonusOpened,
                    showAdIcon: !IAPService.instance.isAdRemovalPurchased,
                  ),

                  const SizedBox(height: 20),

                  // 완료/건너뛰기 버튼
                  _buildBottomButton(context),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context, Color gold) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(
        color: gold.withValues(alpha: 0.3),
        border: Border(bottom: BorderSide(color: gold, width: 2)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('📦', style: TextStyle(fontSize: 20)),
          const SizedBox(width: 8),
          Text(
            l10n.returnRewardTitle,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: gold,
              letterSpacing: 1,
            ),
          ),
          const SizedBox(width: 8),
          const Text('📦', style: TextStyle(fontSize: 20)),
        ],
      ),
    );
  }

  Widget _buildChestSection(
    BuildContext context, {
    required String title,
    required int chestCount,
    required List<ChestReward> rewards,
    required bool isOpened,
    required bool isOpening,
    required VoidCallback onOpen,
    required bool isGold,
    bool enabled = true,
    bool showAdIcon = false,
  }) {
    final gold = RetroColors.goldOf(context);
    final expColor = RetroColors.expOf(context);
    final muted = RetroColors.textMutedOf(context);
    final color = isGold ? gold : expColor;
    final isPaidUser = IAPService.instance.isAdRemovalPurchased;

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        border: Border.all(
          color: (enabled || isOpened)
              ? color.withValues(alpha: 0.5)
              : muted.withValues(alpha: 0.3),
          width: 2,
        ),
      ),
      child: Column(
        children: [
          // 제목
          Text(
            title,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 11,
              color: (enabled || isOpened) ? color : muted,
            ),
          ),
          const SizedBox(height: 12),

          // 상자 아이콘들 또는 보상 목록
          if (isOpened)
            _buildRewardsList(context, rewards)
          else
            _buildChestIcons(chestCount, color, enabled),

          if (!isOpened) ...[
            const SizedBox(height: 12),

            // 오픈 버튼
            GestureDetector(
              onTap: enabled && !isOpening ? onOpen : null,
              child: AnimatedBuilder(
                animation: _shakeAnimation,
                builder: (context, child) {
                  return Transform.translate(
                    offset: isOpening
                        ? Offset(
                            _shakeAnimation.value *
                                2 *
                                ((_animController.value * 10).round() % 2 == 0
                                    ? 1
                                    : -1),
                            0,
                          )
                        : Offset.zero,
                    child: child,
                  );
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  decoration: BoxDecoration(
                    color: enabled
                        ? color.withValues(alpha: 0.3)
                        : muted.withValues(alpha: 0.2),
                    border: Border.all(
                      color: enabled ? color : muted,
                      width: 2,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (isOpening) ...[
                        SizedBox(
                          width: 14,
                          height: 14,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: color,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          l10n.returnRewardOpening,
                          style: TextStyle(
                            fontFamily: 'PressStart2P',
                            fontSize: 10,
                            color: color,
                          ),
                        ),
                      ] else ...[
                        Text(
                          isGold
                              ? l10n.returnRewardOpenChests
                              : (isPaidUser
                                    ? l10n.returnRewardClaimBonusFree
                                    : l10n.returnRewardClaimBonus),
                          style: TextStyle(
                            fontFamily: 'PressStart2P',
                            fontSize: 10,
                            color: enabled ? color : muted,
                          ),
                        ),
                        if (showAdIcon && !isPaidUser) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 4,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white.withValues(alpha: 0.2),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              'AD',
                              style: TextStyle(
                                fontFamily: 'PressStart2P',
                                fontSize: 8,
                                color: enabled ? Colors.white : muted,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ],
                  ),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildChestIcons(int count, Color color, bool enabled) {
    final muted = RetroColors.textMutedOf(context);
    return Wrap(
      alignment: WrapAlignment.center,
      spacing: 8,
      runSpacing: 8,
      children: List.generate(
        count,
        (index) => Text(
          '📦',
          style: TextStyle(fontSize: 24, color: enabled ? null : muted),
        ),
      ),
    );
  }

  Widget _buildRewardsList(BuildContext context, List<ChestReward> rewards) {
    if (rewards.isEmpty) {
      return const Text(
        '(empty)',
        style: TextStyle(
          fontFamily: 'PressStart2P',
          fontSize: 10,
          color: Colors.grey,
        ),
      );
    }

    return Column(
      children: rewards
          .map((reward) => _buildRewardItem(context, reward))
          .toList(),
    );
  }

  Widget _buildRewardItem(BuildContext context, ChestReward reward) {
    final gold = RetroColors.goldOf(context);
    final expColor = RetroColors.expOf(context);

    String icon;
    String text;
    Color color;

    switch (reward.type) {
      case ChestRewardType.equipment:
        icon = '⚔️';
        text = reward.equipment?.name ?? 'Unknown';
        color = _getRarityColor(reward.equipment?.rarity);
        break;
      case ChestRewardType.potion:
        final potion = PotionData.getById(reward.potionId ?? '');
        icon = potion?.type.name == 'hp' ? '❤️' : '💙';
        text = l10n.chestRewardPotionAmount(
          potion?.name ?? 'Potion',
          reward.potionCount ?? 1,
        );
        color = Colors.white;
        break;
      case ChestRewardType.gold:
        icon = '💰';
        text = l10n.chestRewardGoldAmount(reward.gold ?? 0);
        color = gold;
        break;
      case ChestRewardType.experience:
        icon = '⭐';
        text = l10n.chestRewardExpAmount(reward.experience ?? 0);
        color = expColor;
        break;
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(icon, style: const TextStyle(fontSize: 16)),
          const SizedBox(width: 8),
          Flexible(
            child: Text(
              text,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 9,
                color: color,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Color _getRarityColor(ItemRarity? rarity) {
    return switch (rarity) {
      null => Colors.white,
      ItemRarity.common => Colors.grey,
      ItemRarity.uncommon => Colors.green,
      ItemRarity.rare => Colors.blue,
      ItemRarity.epic => Colors.purple,
      ItemRarity.legendary => Colors.orange,
    };
  }

  Widget _buildBottomButton(BuildContext context) {
    final gold = RetroColors.goldOf(context);
    final goldDark = RetroColors.goldDarkOf(context);
    final muted = RetroColors.textMutedOf(context);

    final canComplete = _basicOpened;
    final buttonColor = canComplete ? gold : muted;
    final buttonDark = canComplete ? goldDark : muted.withValues(alpha: 0.5);

    return GestureDetector(
      onTap: canComplete ? _complete : _skip,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: buttonColor.withValues(alpha: 0.2),
          border: Border(
            top: BorderSide(color: buttonColor, width: 2),
            left: BorderSide(color: buttonColor, width: 2),
            bottom: BorderSide(color: buttonDark, width: 2),
            right: BorderSide(color: buttonDark, width: 2),
          ),
        ),
        child: Text(
          canComplete ? 'OK' : l10n.returnRewardSkip,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 12,
            color: buttonColor,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Future<void> _openBasicChests() async {
    if (_basicOpened || _isOpeningBasic) return;

    setState(() {
      _isOpeningBasic = true;
    });

    // 애니메이션 시작
    _animController.repeat();

    // 약간의 딜레이 후 상자 오픈
    await Future<void>.delayed(const Duration(milliseconds: 800));

    final rewards = _rewardsService.claimBasicReward(
      widget.reward,
      widget.playerLevel,
    );

    _animController.stop();

    if (mounted) {
      setState(() {
        _isOpeningBasic = false;
        _basicOpened = true;
        _basicRewards = rewards;
      });
    }
  }

  Future<void> _openBonusChests() async {
    if (_bonusOpened || _isOpeningBonus) return;

    setState(() {
      _isOpeningBonus = true;
    });

    _animController.repeat();

    final rewards = await _rewardsService.claimBonusReward(
      widget.reward,
      widget.playerLevel,
    );

    _animController.stop();

    if (mounted) {
      setState(() {
        _isOpeningBonus = false;
        if (rewards.isNotEmpty) {
          _bonusOpened = true;
          _bonusRewards = rewards;
        }
      });
    }
  }

  void _complete() {
    final allRewards = [..._basicRewards, ..._bonusRewards];
    widget.onClaim(allRewards);
    Navigator.of(context).pop();
  }

  void _skip() {
    widget.onClaim([]);
    Navigator.of(context).pop();
  }
}
