// packages/feature_game_colormatch/lib/screens/colormatch_game_screen.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';
import 'package:feature_common/feature_common.dart';
import '../controllers/colormatch_controller.dart';
import '../models/colormatch_models.dart';

class ColorMatchGameScreen extends StatefulWidget {
  const ColorMatchGameScreen({super.key});

  @override
  State<ColorMatchGameScreen> createState() => _ColorMatchGameScreenState();
}

class _ColorMatchGameScreenState extends State<ColorMatchGameScreen> {
  bool _isDialogShowing = false;

  void _showGameCompletion(ColorMatchController controller) async {
    String formatMatchScore(int primary, int? secondary) {
      final correct = primary;
      final incorrect = secondary ?? 0;
      return '${correct}개 맞춤 (${incorrect}개 틀림)';
    }

    Future<void> saveMatchProgress(String playerName) async {
      // [🔥 핵심] 정답률 70% 미만이면 레벨 저장 안 함
      final int total = controller.difficulty.totalRounds;
      final int correct = controller.score;
      final double accuracy = (total > 0) ? (correct / total) : 0.0;
      const double passingThreshold = 0.7; 

      if (accuracy < passingThreshold) {
        debugPrint("레벨 클리어 실패: 정답률 ${(accuracy * 100).toStringAsFixed(1)}% < 70%");
        return;
      }

      final identityService = IdentityService();
      final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'COLOR_MATCH');
      if (currentMaxLevel < 99) {
        if (controller.difficulty.levelIndex >= currentMaxLevel) {
          int nextLevel = controller.difficulty.levelIndex + 1;
          if (nextLevel > ColorMatchDifficulties.allDifficulties.length) {
            await identityService.saveMaxUnlockedLevel(99, gameType: 'COLOR_MATCH');
          } else {
            await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'COLOR_MATCH');
          }
        }
      }
    }

    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GameCompletionScreen(
          args: GameResultArgs(
            gameType: 'COLOR_MATCH',
            contextId: controller.difficulty.contextId,
            primaryScore: controller.score,
            secondaryScore: controller.incorrectCount,
            userId: controller.userId,
            userName: controller.userName,
            scoreFormatter: formatMatchScore,
            onProgressSave: saveMatchProgress,
          ),
        ),
      ),
    );

    if (mounted && Navigator.canPop(context)) {
      Navigator.pop(context);
    }
  }

  // 🔽 피드백 위젯 빌더
  Widget _buildFeedbackWidget(ColorMatchController controller, ThemeData theme) {
    if (!controller.showFeedback) {
      // 라운드 타이머가 실행 중이면 남은 시간을 표시
      if (controller.remainingChallengeTime > 0) {
        return SizedBox(
          height: 60,
          child: Center(
            child: Text(
              '${controller.remainingChallengeTime}s',
              style: TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: theme.colorScheme.primary,
              ),
            ),
          ),
        );
      }
      return const SizedBox(height: 60);
    }

    // 피드백 메시지 결정
    String text;
    Color color;

    if (controller.isTimeOutFailure) {
      text = "시간 초과! ⏱️";
      color = Colors.orange;
    } else if (controller.isLastAnswerCorrect) {
      text = "정답! 👍";
      color = Colors.green;
    } else {
      text = "오답! 👎";
      color = theme.colorScheme.error;
    }

    return SizedBox(
      height: 60,
      child: Center(
        child: Text(
          text,
          style: TextStyle(
            fontSize: 32,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ),
    );
  }

  // 🔽 지침 텍스트 빌더 (RichText)
  TextSpan _buildInstructionTextSpan(MatchMode mode, ThemeData theme) {
    const TextStyle defaultStyle = TextStyle(fontSize: 18);
    const TextStyle boldStyle = TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: Colors.black);

    switch (mode) {
      case MatchMode.matchColor:
        return TextSpan(
          style: defaultStyle,
          children: [
            const TextSpan(text: '아래 단어의 "'),
            TextSpan(text: '글자 색상', style: boldStyle.copyWith(color: theme.colorScheme.primary)),
            const TextSpan(text: '"에 해당하는 버튼을 누르세요.'),
          ],
        );
      case MatchMode.matchWord:
        return const TextSpan(
          style: defaultStyle,
          children: [
            TextSpan(text: '아래 단어가 "'),
            TextSpan(text: '표현하는 의미', style: boldStyle),
            TextSpan(text: '"에 해당하는 버튼을 누르세요.'),
          ],
        );
      case MatchMode.matchBackground:
        return const TextSpan(
          style: defaultStyle,
          children: [
            TextSpan(text: '아래 단어의 "'),
            TextSpan(text: '배경 색상', style: boldStyle),
            TextSpan(text: '"에 해당하는 버튼을 누르세요.'),
          ],
        );
      default:
        return const TextSpan(text: '버튼을 누르세요.');
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = context.watch<ColorMatchController>();
    
    if (controller.isGameCompleted && !_isDialogShowing) {
      _isDialogShowing = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _showGameCompletion(controller);
      });
    }

    final seconds = controller.secondsElapsed;
    final timeStr = "${(seconds ~/ 60).toString().padLeft(2, '0')}:${(seconds % 60).toString().padLeft(2, '0')}";
    final MatchChallenge challenge = controller.currentChallenge;
    final theme = Theme.of(context);
    final bool isInputBlocked = controller.showFeedback || controller.isGameCompleted;

    return Scaffold(
      appBar: AppBar(
        title: Text(controller.difficulty.name),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 16.0),
            child: Center(
              // 🔽 점수 및 라운드 정보 표시
              child: Text(
                'RND: ${controller.currentRound}/${controller.difficulty.totalRounds} | S: ${controller.score} / W: ${controller.incorrectCount} | T: $timeStr',
                style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 🔽 피드백 영역
            _buildFeedbackWidget(controller, theme),
            const SizedBox(height: 40),

            // 🔽 지침 영역 (RichText)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Text.rich(
                _buildInstructionTextSpan(controller.currentMatchMode, theme),
                textAlign: TextAlign.center,
              ),
            ),
            const SizedBox(height: 40),

            // 🔽 문제 제시 영역 (배경색 + 음영)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              decoration: BoxDecoration(
                color: challenge.backgroundColor, 
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: Colors.black12, width: 2),
              ),
              child: Text(
                challenge.displayedWord,
                style: TextStyle(
                  fontSize: 60,
                  fontWeight: FontWeight.w900,
                  color: challenge.textColor,
                  shadows: const [
                    Shadow(
                      blurRadius: 3.0,
                      color: Colors.black, // 글자 가독성을 위한 검은색 음영
                      offset: Offset(1.0, 1.0),
                    ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 80),

            // 🔽 버튼 영역
            Wrap(
              spacing: 16.0,
              runSpacing: 16.0,
              alignment: WrapAlignment.center,
              children: controller.difficulty.colorSet.map((matchColor) {
                return SizedBox(
                  width: 150,
                  height: 60,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: matchColor.color,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      padding: EdgeInsets.zero,
                    ),
                    onPressed: isInputBlocked
                        ? null
                        : () => controller.checkAnswer(matchColor.color),
                    child: Text(
                      matchColor.name,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: theme.colorScheme.onSurface,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ],
        ),
      ),
    );
  }
}