// packages/feature_game_mathquiz/lib/screens/math_quiz_lobby_screen.dart
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// [C] 공통 서비스 (service_api)
import 'package:service_api/service_api.dart';
// [A] 공통 UI (feature_common)
import 'package:feature_common/feature_common.dart';
// [B] 이 패키지 (mathquiz)
import 'math_quiz_screen.dart';
import '../controllers/math_quiz_controller.dart';
import '../models/math_quiz_difficulty.dart'; // 👈 [추가]

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

  @override
  State<MathQuizLobbyScreen> createState() => _MathQuizLobbyScreenState();
}

class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
  int _maxUnlockedLevel = 1;
  Map<int, (int, int)> _rankHistory = {};
  bool _isLoading = false;

  late final SessionNotifier _sessionNotifier;
  late final LobbyHelperService _lobbyHelper;
  // [🔥 수정] 서비스를 직접 생성 (Provider로 읽지 않음)
  final PuzzleService _puzzleService = PuzzleService();
  final IdentityService _identityService = IdentityService();

  @override
  void initState() {
    super.initState();
    _sessionNotifier = context.read<SessionNotifier>();

    // [🔥 수정] 헬퍼 서비스 초기화 (직접 생성한 서비스 주입)
    _lobbyHelper = LobbyHelperService(
      identityService: _identityService,
      puzzleService: _puzzleService,
    );

    _loadProgress(forceRefreshRanks: true);
  }

  /// [수정됨] 공통 헬퍼를 사용
  Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
    // 1. (가벼움) 레벨 정보 새로고침
    final maxLevel = await _lobbyHelper.loadMaxLevel('MATH_QUIZ');
    if (mounted) {
      setState(() {
        _maxUnlockedLevel = maxLevel;
      });
    }

    // 2. (무거움) 랭킹 정보 새로고침 (필요할 때만)
    if (!forceRefreshRanks) return;

    final String? myName = _sessionNotifier.session?.userName;
    if (myName == null) return;

    try {
      final rankHistory = await _lobbyHelper.loadRankHistory<MathQuizDifficulty>(
        gameType: 'MATH_QUIZ',
        myName: myName,
        allLevels: MathQuizDifficulties.allDifficulties,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) {
        setState(() {
          _rankHistory = rankHistory;
        });
      }
    } catch (e) {
      log("MathQuizLobbyScreen: 랭킹 확인 실패: $e");
    }
  }

  /// 🔽 [수정 없음] 게임 시작 함수
  Future<void> _startGame(MathQuizDifficulty level) async {
    setState(() {
      _isLoading = true;
    });

    try {
      final session = _sessionNotifier.session;
      if (session == null) {
        throw Exception("세션이 로드되지 않았습니다.");
      }

      // 1. 컨트롤러 생성 및 새 게임 시작 (제너레이터 호출)
      final controller = MathQuizController();
      controller.startNewGame(level, session.userId, session.userName);

      if (mounted) {
        await Navigator.push(
          context,
          MaterialPageRoute(
            // 2. 컨트롤러를 게임 화면에 주입
            builder: (context) => ChangeNotifierProvider.value(
              value: controller,
              child: const MathQuizScreen(),
            ),
          ),
        );

        // 3. 게임에서 돌아오면 레벨 잠금 상태만 새로고침
        _loadProgress(forceRefreshRanks: false);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('게임 로딩/생성 실패: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    context.watch<ThemeNotifier>();
    context.watch<SessionNotifier>();

    final bool allLevelsUnlocked =
        _maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
    final theme = Theme.of(context);

    return CommonGameShell(
      title: '계산 퀴즈',
      onRankingPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'MATH_QUIZ',
              difficulties: MathQuizDifficulties.allDifficulties,
              initialDifficultyName:
                  MathQuizDifficulties.getLevel(_maxUnlockedLevel).name,
            ),
          ),
        );
      },
      body: LayoutBuilder(
        builder: (context, constraints) {
          const double maxContentRatio = 0.6;
          final double constrainedWidth =
              (constraints.maxHeight * maxContentRatio) > 500
                  ? 500
                  : (constraints.maxHeight * maxContentRatio);
          return Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: constrainedWidth),
              child: Column(
                children: [
                  Expanded(
                    child: RefreshIndicator(
                      onRefresh: () => _loadProgress(forceRefreshRanks: true),
                      child: ListView.builder(
                        itemCount: MathQuizDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          final MathQuizDifficulty level =
                              MathQuizDifficulties.allDifficulties[index];
                          final bool isUnlocked = allLevelsUnlocked ||
                              level.levelIndex <= _maxUnlockedLevel;
                          final (int oldRank, int currentRank) =
                              _rankHistory[level.levelIndex] ?? (0, 0);

                          Widget? trailingWidget = isUnlocked
                              ? const Icon(Icons.play_arrow_rounded)
                              : null;
                          String? subtitleText;
                          Color? subtitleColor;

                          if (currentRank > 0) {
                            String rankStr = "${currentRank}위";
                            if (oldRank > 0) {
                              int change = oldRank - currentRank;
                              if (change > 0) {
                                subtitleText = "$rankStr (▲ $change)";
                                subtitleColor = Colors.green;
                                trailingWidget = const Icon(
                                    Icons.arrow_circle_up_rounded,
                                    color: Colors.green,
                                    size: 28);
                              } else if (change < 0) {
                                subtitleText = "$rankStr (▼ ${change.abs()})";
                                subtitleColor = Colors.red;
                                trailingWidget = const Icon(
                                    Icons.arrow_circle_down_rounded,
                                    color: Colors.red,
                                    size: 28);
                              } else {
                                subtitleText = "$rankStr (유지)";
                                subtitleColor = Colors.grey;
                                trailingWidget = const Icon(
                                    Icons.check_circle_outline_rounded,
                                    color: Colors.grey,
                                    size: 28);
                              }
                            } else {
                              subtitleText = "$rankStr (신규 진입)";
                              subtitleColor = Colors.blue;
                              trailingWidget = const Icon(
                                  Icons.new_releases_rounded,
                                  color: Colors.blue,
                                  size: 28);
                            }
                          } else {
                            if (oldRank > 0) {
                              subtitleText = "랭킹 이탈 (이전 ${oldRank}위)";
                              subtitleColor = Colors.orange;
                              trailingWidget = const Icon(
                                  Icons.warning_amber_rounded,
                                  color: Colors.orange,
                                  size: 28);
                            }
                          }

                          return Card(
                            margin: const EdgeInsets.symmetric(
                                horizontal: 16.0, vertical: 4.0),
                            child: ListTile(
                              leading: Icon(
                                isUnlocked
                                    ? Icons.lock_open_rounded
                                    : Icons.lock_rounded,
                                color: isUnlocked ? theme.primaryColor : Colors.grey,
                              ),
                              title: Text(level.name,
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: isUnlocked
                                        ? FontWeight.bold
                                        : FontWeight.normal,
                                    color: isUnlocked
                                        ? theme.textTheme.bodyLarge?.color
                                        : Colors.grey,
                                  )),
                              subtitle: subtitleText != null
                                  ? Text(subtitleText,
                                      style: TextStyle(
                                          color: subtitleColor,
                                          fontWeight: FontWeight.bold))
                                  : null,
                              trailing: trailingWidget,
                              onTap: isUnlocked && !_isLoading
                                  ? () => _startGame(level)
                                  : null,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}