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/math_quiz_controller.dart';
import '../models/math_quiz_difficulty.dart';
import '../models/math_quiz_models.dart';

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

  @override
  State<MathQuizScreen> createState() => _MathQuizScreenState();
}

class _MathQuizScreenState extends State<MathQuizScreen> {
  bool _isDialogShowing = false;

  // ... ( _showGameCompletion 메서드는 이전과 동일 ... )
  void _showGameCompletion(MathQuizController controller) async {
    String formatMathQuizScore(int primary, int? secondary) {
      final blanksCount = primary;
      final time = (secondary ?? 0).toString();
      return '총 ${blanksCount}칸 (${time}초)';
    }

    Future<void> saveMathQuizProgress(String playerName) async {
      final identityService = IdentityService();
      final int currentMaxLevel =
          await identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
      if (currentMaxLevel < 99) {
        if (controller.difficulty.levelIndex >= currentMaxLevel) {
          int nextLevel = controller.difficulty.levelIndex + 1;
          if (nextLevel > MathQuizDifficulties.allDifficulties.length) {
            await identityService.saveMaxUnlockedLevel(99,
                gameType: 'MATH_QUIZ');
          } else {
            await identityService.saveMaxUnlockedLevel(nextLevel,
                gameType: 'MATH_QUIZ');
          }
        }
      }
    }

    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GameCompletionScreen(
          args: GameResultArgs(
            gameType: 'MATH_QUIZ',
            contextId: controller.difficulty.contextId,
            primaryScore: controller.totalBlanksFilled,
            secondaryScore: controller.secondsElapsed,
            userId: controller.userId,
            userName: controller.userName,
            scoreFormatter: formatMathQuizScore,
            onProgressSave: saveMathQuizProgress,
          ),
        ),
      ),
    );

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

  @override
  Widget build(BuildContext context) {
    final controller = context.watch<MathQuizController>();

    if (controller.isGameCompleted && !_isDialogShowing) {
      _isDialogShowing = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _showGameCompletion(controller);
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('Lv. ${controller.difficulty.levelIndex}'),
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: _buildTriesWidget(controller.remainingTries),
            ),
          ),
          Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                '${controller.currentPuzzleIndex + 1} / ${controller.totalPuzzlesInLevel}',
                style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 20.0),
              child: Text(
                '${(controller.secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(controller.secondsElapsed % 60).toString().padLeft(2, '0')}',
                style:
                    const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          bool isLandscape = constraints.maxWidth > constraints.maxHeight;
          if (isLandscape) {
            return _buildLandscapeLayout(context, controller);
          } else {
            return _buildPortraitLayout(context, controller);
          }
        },
      ),
    );
  }

  Widget _buildTriesWidget(int tries) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(3, (index) {
        return Icon(
          index < tries ? Icons.favorite : Icons.favorite_border,
          color: Colors.redAccent,
          size: 24,
        );
      }),
    );
  }

  Widget _buildPortraitLayout(
      BuildContext context, MathQuizController controller) {
    return Column(
      children: [
        Expanded(
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: _buildPuzzleGrid(context, controller),
            ),
          ),
        ),
        _buildKeypad(context, controller),
      ],
    );
  }

  Widget _buildLandscapeLayout(
      BuildContext context, MathQuizController controller) {
    return Row(
      children: [
        Expanded(
          flex: 6,
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: _buildPuzzleGrid(context, controller),
            ),
          ),
        ),
        Expanded(
          flex: 4,
          child: _buildKeypad(context, controller),
        ),
      ],
    );
  }

  Widget _buildPuzzleGrid(BuildContext context, MathQuizController controller) {
    final puzzle = controller.puzzle;
    final userAnswers = controller.userAnswers;
    final int crossAxisCount = puzzle.gridCrossAxisCount;

    int blankIndex = 0;

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: puzzle.gridCells.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
      ),
      itemBuilder: (context, index) {
        final String part = puzzle.gridCells[index];

        if (part == "?") {
          final int currentBlankIndex = blankIndex;
          blankIndex++;
          return _buildBlankBox(
            context,
            controller,
            currentBlankIndex,
            (currentBlankIndex < userAnswers.length)
                ? userAnswers[currentBlankIndex]
                : null,
          );
        } else if (part == " ") {
          return Container();
        } else {
          return Center(
            child: FittedBox(
              fit: BoxFit.contain,
              child: Padding(
                padding: const EdgeInsets.all(4.0),
                child: Text(
                  part,
                  style: const TextStyle(
                      fontSize: 32, fontWeight: FontWeight.bold),
                ),
              ),
            ),
          );
        }
      },
    );
  }

  Widget _buildBlankBox(BuildContext context, MathQuizController controller,
      int index, String? value) {
    final theme = Theme.of(context);
    final bool isSelected = (controller.selectedBlankIndex == index);
    final bool isWrong = controller.isWrongAnswer;
    final bool isRevealing = controller.isRevealingAnswer;

    Color borderColor;
    Color textColor;

    if (isRevealing) {
      borderColor = theme.colorScheme.primary;
      textColor = theme.colorScheme.primary;
    } else if (isWrong) {
      borderColor = theme.colorScheme.error;
      textColor = theme.colorScheme.onSurfaceVariant;
    } else if (isSelected) {
      borderColor = theme.colorScheme.primary;
      textColor = theme.colorScheme.onSurfaceVariant;
    } else {
      borderColor = Colors.transparent;
      textColor = theme.colorScheme.onSurfaceVariant;
    }

    return AspectRatio(
      aspectRatio: 1 / 1,
      child: GestureDetector(
        onTap: () => controller.onBlankTapped(index),
        child: Container(
          margin: const EdgeInsets.all(4.0),
          decoration: BoxDecoration(
            color: theme.colorScheme.surfaceVariant,
            border: Border.all(
              color: borderColor,
              width: 3,
            ),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: FittedBox(
              fit: BoxFit.contain,
              child: Padding(
                padding: const EdgeInsets.all(4.0),
                child: Text(
                  value ?? '',
                  style: TextStyle(
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                    color: textColor,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// [🔥 수정됨] 키패드 UI 빌더 (동적 필터링)
  Widget _buildKeypad(BuildContext context, MathQuizController controller) {
    final puzzle = controller.puzzle;
    final theme = Theme.of(context);
    final bool isDisabled = controller.isRevealingAnswer;

    final PuzzleBlankType? selectedType = controller.currentSelectedBlankType;

    // [🔥 최종 확인] 헬퍼 함수
    bool isOperator(String val) => ['/', '*', '-', '+'].contains(val);
    bool isNumber(String val) => int.tryParse(val) != null;

    // [🔥 최종 수정] 타입에 따라 옵션 필터링
    List<String> availableOptions = [];
    if (selectedType == PuzzleBlankType.number) {
      // 숫자가 필요하면 숫자만 필터링
      availableOptions = puzzle.options.where((opt) => isNumber(opt)).toList();
    } else if (selectedType == PuzzleBlankType.operator) {
      // 연산자가 필요하면 연산자만 필터링
      availableOptions = puzzle.options.where((opt) => isOperator(opt)).toList();
    }

    final int totalButtonCount = availableOptions.length + 1; // 필터링된 옵션 + 지우기

    return Container(
      // ... (GridView.builder 이하 로직은 동일) ...
      padding: const EdgeInsets.all(8.0),
      decoration: BoxDecoration(
        color: theme.scaffoldBackgroundColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5, // 5열
          childAspectRatio: 1.5,
          mainAxisSpacing: 8,
          crossAxisSpacing: 8,
        ),
        itemCount: totalButtonCount,
        itemBuilder: (context, index) {
          if (index == availableOptions.length) {
            return FilledButton.tonal(
              onPressed: isDisabled ? null : () => controller.onClearTapped(),
              child: const Icon(Icons.backspace_outlined),
            );
          }

          final String option = availableOptions[index];
          return FilledButton(
            onPressed: isDisabled ? null : () => controller.onOptionTapped(option),
            child: Text(
              option,
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
          );
        },
      ),
    );
  }
}