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_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 problemCount = primary;
      final time = (secondary ?? 0).toString();
      return '${problemCount}개 (${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.puzzle.solutions.length, 
            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(controller.difficulty.name),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 20.0),
            child: Center(
              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 _buildPortraitLayout(BuildContext context, MathQuizController controller) {
    return Column(
      children: [
        Expanded(
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              // [수정] _buildPuzzleGrid를 항상 호출
              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),
              // [수정] _buildPuzzleGrid를 항상 호출
              child: _buildPuzzleGrid(context, controller),
            ),
          ),
        ),
        Expanded(
          flex: 4, // 키패드 영역
          child: _buildKeypad(context, controller),
        ),
      ],
    );
  }

  // ❌ [삭제] _buildEquationList 메서드 삭제

  /// [수정] _buildEquationGrid -> _buildPuzzleGrid
  /// (모든 퍼즐을 그리는 유일한 빌더)
  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,
            userAnswers[currentBlankIndex],
          );
        } else if (part == " ") {
          // " " (빈 공간)
          return Container();
        } else {
          // 숫자나 기호일 경우
          return Center(
            child: Text(
              part,
              style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
            ),
          );
        }
      },
    );
  }

  /// [수정] _buildBlankBox (isGrid 파라미터 삭제)
  Widget _buildBlankBox(BuildContext context, MathQuizController controller, int index, String? value) {
    final theme = Theme.of(context);
    final bool isSelected = (controller.selectedBlankIndex == index);

    // [수정] 그리드 셀의 크기는 GridView가 결정하므로
    // AspectRatio를 사용해 1:1 비율 유지
    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: isSelected ? theme.colorScheme.primary : Colors.transparent,
              width: 3,
            ),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            // [수정] 폰트 크기를 FittedBox로 자동 조절
            child: FittedBox(
              fit: BoxFit.contain,
              child: Padding(
                padding: const EdgeInsets.all(4.0),
                child: Text(
                  value ?? '', 
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: theme.colorScheme.onSurfaceVariant,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 2. 키패드 UI 빌더
  Widget _buildKeypad(BuildContext context, MathQuizController controller) {
    // ... (이하 키패드 로직은 동일) ...
    final puzzle = controller.puzzle;
    final theme = Theme.of(context);

    return Container(
      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: puzzle.options.length + 1, // 옵션 + 지우기 버튼
        itemBuilder: (context, index) {
          
          if (index == puzzle.options.length) {
            return FilledButton.tonal(
              onPressed: () => controller.onClearTapped(),
              child: const Icon(Icons.backspace_outlined),
            );
          }
          
          final String option = puzzle.options[index];
          return FilledButton(
            onPressed: () => controller.onOptionTapped(option),
            child: Text(
              option,
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
          );
        },
      ),
    );
  }
}