import 'package:flutter/material.dart';

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

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

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

  /// 보상 수령 콜백 (totalGold)
  final void Function(int totalGold) onClaim;

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

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

class _ReturnRewardsDialogState extends State<ReturnRewardsDialog> {
  bool _basicClaimed = false;
  bool _bonusClaimed = false;
  bool _isClaimingBonus = false;
  int _totalClaimed = 0;

  final _rewardsService = ReturnRewardsService.instance;

  @override
  Widget build(BuildContext context) {
    final gold = RetroColors.goldOf(context);
    final goldDark = RetroColors.goldDarkOf(context);
    final panelBg = RetroColors.panelBgOf(context);
    final borderColor = RetroColors.borderOf(context);
    final expColor = RetroColors.expOf(context);
    final isPaidUser = IAPService.instance.isAdRemovalPurchased;

    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: const BoxConstraints(maxWidth: 360),
        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: 11,
                      color: gold.withValues(alpha: 0.8),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 20),

                  // 기본 보상
                  _buildRewardSection(
                    context,
                    title: l10n.returnRewardBasic,
                    gold: widget.reward.goldReward,
                    color: gold,
                    colorDark: goldDark,
                    claimed: _basicClaimed,
                    onClaim: _claimBasic,
                    buttonText: l10n.returnRewardClaim,
                  ),
                  const SizedBox(height: 16),

                  // 보너스 보상
                  _buildRewardSection(
                    context,
                    title: l10n.returnRewardBonus,
                    gold: widget.reward.bonusGold,
                    color: expColor,
                    colorDark: expColor.withValues(alpha: 0.6),
                    claimed: _bonusClaimed,
                    onClaim: _claimBonus,
                    buttonText: l10n.returnRewardClaimBonus,
                    showAdIcon: !isPaidUser,
                    isLoading: _isClaimingBonus,
                    enabled: _basicClaimed && !_bonusClaimed,
                  ),
                  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: [
          Text('🎁', style: TextStyle(fontSize: 20, color: gold)),
          const SizedBox(width: 8),
          Text(
            l10n.returnRewardTitle,
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 14,
              color: gold,
              letterSpacing: 1,
            ),
          ),
          const SizedBox(width: 8),
          Text('🎁', style: TextStyle(fontSize: 20, color: gold)),
        ],
      ),
    );
  }

  Widget _buildRewardSection(
    BuildContext context, {
    required String title,
    required int gold,
    required Color color,
    required Color colorDark,
    required bool claimed,
    required VoidCallback onClaim,
    required String buttonText,
    bool showAdIcon = false,
    bool isLoading = false,
    bool enabled = true,
  }) {
    final muted = RetroColors.textMutedOf(context);

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

          // 골드 표시
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('💰', style: TextStyle(fontSize: 20)),
              const SizedBox(width: 8),
              Text(
                l10n.returnRewardGold(gold),
                style: TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 14,
                  color: claimed ? muted : color,
                  decoration: claimed ? TextDecoration.lineThrough : null,
                ),
              ),
              if (claimed) ...[
                const SizedBox(width: 8),
                Text(
                  '✓',
                  style: TextStyle(
                    fontSize: 18,
                    color: RetroColors.expOf(context),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ],
          ),

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

            // 수령 버튼
            GestureDetector(
              onTap: enabled && !isLoading ? onClaim : null,
              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 (isLoading) ...[
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: color,
                        ),
                      ),
                      const SizedBox(width: 8),
                    ],
                    Text(
                      buttonText,
                      style: TextStyle(
                        fontFamily: 'PressStart2P',
                        fontSize: 11,
                        color: enabled ? color : muted,
                      ),
                    ),
                    if (showAdIcon && !isLoading) ...[
                      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 _buildBottomButton(BuildContext context) {
    final gold = RetroColors.goldOf(context);
    final goldDark = RetroColors.goldDarkOf(context);
    final muted = RetroColors.textMutedOf(context);

    final canComplete = _basicClaimed;
    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,
        ),
      ),
    );
  }

  void _claimBasic() {
    if (_basicClaimed) return;

    final claimed = _rewardsService.claimBasicReward(widget.reward);
    setState(() {
      _basicClaimed = true;
      _totalClaimed += claimed;
    });
  }

  Future<void> _claimBonus() async {
    if (_bonusClaimed || _isClaimingBonus) return;

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

    final bonus = await _rewardsService.claimBonusReward(widget.reward);

    if (mounted) {
      setState(() {
        _isClaimingBonus = false;
        if (bonus > 0) {
          _bonusClaimed = true;
          _totalClaimed += bonus;
        }
      });
    }
  }

  void _complete() {
    widget.onClaim(_totalClaimed);
    Navigator.of(context).pop();
  }

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