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/iap_service.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';
import 'package:asciineverdie/src/shared/widgets/retro_widgets.dart';

/// 능력치 표시 섹션
class StatsSection extends StatelessWidget {
  const StatsSection({
    super.key,
    required this.str,
    required this.con,
    required this.dex,
    required this.intelligence,
    required this.wis,
    required this.cha,
    required this.canRoll,
    required this.canUndo,
    required this.rollsRemaining,
    required this.availableUndos,
    required this.onRoll,
    required this.onUndo,
  });

  final int str;
  final int con;
  final int dex;
  final int intelligence;
  final int wis;
  final int cha;
  final bool canRoll;
  final bool canUndo;
  final int rollsRemaining;
  final int availableUndos;
  final VoidCallback onRoll;
  final VoidCallback onUndo;

  int get _total => str + con + dex + intelligence + wis + cha;

  /// Total 색상 결정 (원본 규칙)
  /// 63+18(81) 이상 = 빨강, 4*18(72) 초과 = 노랑
  /// 63-18(45) 이하 = 회색, 3*18(54) 미만 = 은색
  /// 그 외 = 흰색
  Color _getTotalColor() {
    final total = _total;
    if (total >= 81) return Colors.red;
    if (total > 72) return Colors.yellow;
    if (total <= 45) return Colors.grey;
    if (total < 54) return Colors.grey.shade400;
    return Colors.white;
  }

  @override
  Widget build(BuildContext context) {
    final l10n = L10n.of(context);
    return RetroPanel(
      title: l10n.statsTitle,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 스탯 그리드
          Row(
            children: [
              Expanded(
                child: _StatTile(label: l10n.statStr, value: str),
              ),
              Expanded(
                child: _StatTile(label: l10n.statCon, value: con),
              ),
              Expanded(
                child: _StatTile(label: l10n.statDex, value: dex),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: _StatTile(label: l10n.statInt, value: intelligence),
              ),
              Expanded(
                child: _StatTile(label: l10n.statWis, value: wis),
              ),
              Expanded(
                child: _StatTile(label: l10n.statCha, value: cha),
              ),
            ],
          ),
          const SizedBox(height: 12),

          // Total
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: _getTotalColor().withValues(alpha: 0.2),
              border: Border.all(color: _getTotalColor(), width: 2),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  l10n.total.toUpperCase(),
                  style: const TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                    color: RetroColors.textLight,
                  ),
                ),
                Text(
                  '$_total',
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: _getTotalColor(),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),

          // Roll 버튼들
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _UndoButton(canUndo: canUndo, onPressed: onUndo),
              const SizedBox(width: 16),
              _RollButton(
                canRoll: canRoll,
                rollsRemaining: rollsRemaining,
                onPressed: onRoll,
              ),
            ],
          ),
          // 남은 횟수 표시
          Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Center(
              child: Text(
                canUndo
                    ? game_l10n.uiUndoAndRolls(availableUndos, rollsRemaining)
                    : game_l10n.uiRollsOnly(rollsRemaining),
                style: const TextStyle(
                  fontFamily: 'PressStart2P',
                  fontSize: 11,
                  color: RetroColors.textDisabled,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 스탯 타일 위젯
class _StatTile extends StatelessWidget {
  const _StatTile({required this.label, required this.value});

  final String label;
  final int value;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(4),
      padding: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        color: RetroColors.panelBgLight,
        border: Border.all(color: RetroColors.panelBorderInner),
      ),
      child: Column(
        children: [
          Text(
            label.toUpperCase(),
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 13,
              color: RetroColors.gold,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            '$value',
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 17,
              fontWeight: FontWeight.bold,
              color: RetroColors.textLight,
            ),
          ),
        ],
      ),
    );
  }
}

/// 되돌리기 버튼
class _UndoButton extends StatelessWidget {
  const _UndoButton({required this.canUndo, required this.onPressed});

  final bool canUndo;
  final VoidCallback onPressed;

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

    return GestureDetector(
      onTap: canUndo ? onPressed : null,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: canUndo
              ? RetroColors.panelBgLight
              : RetroColors.panelBg.withValues(alpha: 0.5),
          border: Border.all(
            color: canUndo ? RetroColors.panelBorderInner : RetroColors.panelBg,
            width: 2,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 무료 유저는 광고 아이콘 표시
            if (!isPaidUser && canUndo) ...[
              const Icon(Icons.play_circle, size: 14, color: RetroColors.gold),
              const SizedBox(width: 4),
            ],
            Icon(
              Icons.undo,
              size: 14,
              color: canUndo ? RetroColors.textLight : RetroColors.textDisabled,
            ),
            const SizedBox(width: 4),
            Text(
              l10n.unroll.toUpperCase(),
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: canUndo
                    ? RetroColors.textLight
                    : RetroColors.textDisabled,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 굴리기 버튼
class _RollButton extends StatelessWidget {
  const _RollButton({
    required this.canRoll,
    required this.rollsRemaining,
    required this.onPressed,
  });

  final bool canRoll;
  final int rollsRemaining;
  final VoidCallback onPressed;

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

    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: RetroColors.panelBgLight,
          border: Border.all(color: RetroColors.gold, width: 2),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 0회일 때 광고 아이콘 표시
            if (!canRoll) ...[
              const Icon(Icons.play_circle, size: 14, color: RetroColors.gold),
              const SizedBox(width: 4),
            ],
            const Icon(Icons.casino, size: 14, color: RetroColors.gold),
            const SizedBox(width: 4),
            Text(
              canRoll
                  ? '${l10n.roll.toUpperCase()} ($rollsRemaining)'
                  : l10n.roll.toUpperCase(),
              style: const TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: RetroColors.gold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
