// packages/feature_game_colormatch/lib/screens/colormatch_lobby_screen.dart

import 'dart:developer';
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 'colormatch_game_screen.dart';
import '../models/colormatch_models.dart';
import '../controllers/colormatch_controller.dart'; 

class ColorMatchLobbyScreen extends StatefulWidget {
  const ColorMatchLobbyScreen({ super.key });
  @override
  State<ColorMatchLobbyScreen> createState() => _ColorMatchLobbyScreenState();
}

class _ColorMatchLobbyScreenState extends State<ColorMatchLobbyScreen> {
  int _maxUnlockedLevel = 1; 
  Map<int, (int, int)> _rankHistory = {};
  bool _isLoading = false;
  
  late final SessionNotifier _sessionNotifier;
  late final LobbyHelperService _lobbyHelper;
  final IdentityService _identityService = IdentityService(); // 👈 레벨 잠금 해제용

  @override
  void initState() {
    super.initState();
    _sessionNotifier = context.read<SessionNotifier>();
    
    _lobbyHelper = LobbyHelperService(
      identityService: context.read<IdentityService>(),
      puzzleService: context.read<PuzzleService>(),
    );
    
    _loadProgress(forceRefreshRanks: true);
  }

  /// 🔽 공통 헬퍼를 사용한 로드 로직
  Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
    final maxLevel = await _lobbyHelper.loadMaxLevel('COLOR_MATCH');
    if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; }); }

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

    try {
      final rankHistory = await _lobbyHelper.loadRankHistory<ColorMatchDifficulty>(
        gameType: 'COLOR_MATCH',
        myName: myName,
        allLevels: ColorMatchDifficulties.allDifficulties,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) { setState(() { _rankHistory = rankHistory; }); }
      log("색상 매칭 랭킹 변동 확인 완료. (유저: $myName)");
    } catch (e) {
      log("ColorMatchLobbyScreen: 랭킹 확인 실패: $e");
    }
  }


  /// 🔽 게임 시작 로직
  Future<void> _startGame(ColorMatchDifficulty level) async {
    setState(() { _isLoading = true; });

    final session = _sessionNotifier.session;
    if (session == null) {
      log("세션이 로드되지 않아 게임을 시작할 수 없습니다.");
      setState(() { _isLoading = false; });
      return;
    }
    
    final String userId = session.userId;
    final String? userName = session.userName;

    // 1. 컨트롤러 생성 및 새 게임 시작
    final gameController = ColorMatchController();
    gameController.setUserInfo(userId, userName);
    gameController.startNewGame(level); // 👈 문제 생성 및 시작

    setState(() { _isLoading = false; });
    if (!mounted) return;

    // 2. 게임 화면으로 이동 (Controller 주입)
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => 
          ChangeNotifierProvider.value(
            value: gameController,
            child: const ColorMatchGameScreen(),
          ),
      ),
    );
    
    // 3. 게임 종료 후 레벨 잠금 상태만 새로고침
    _loadProgress(forceRefreshRanks: false);
  }

  @override
  Widget build(BuildContext context) {
    context.watch<ThemeNotifier>();
    context.watch<SessionNotifier>();
    
    final bool allLevelsUnlocked = _maxUnlockedLevel >= ColorMatchDifficulties.allDifficulties.length;
    final theme = Theme.of(context);
    
    // 🔽 [핵심] CommonGameShell 사용
    return CommonGameShell(
      title: '색상 인지 퀴즈 (Stroop)',
      onRankingPressed: () {
        // 랭킹 화면 호출
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'COLOR_MATCH',
              difficulties: ColorMatchDifficulties.allDifficulties,
              initialDifficultyName: ColorMatchDifficulties.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: ColorMatchDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          final ColorMatchDifficulty level = ColorMatchDifficulties.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}위";
                            // ... (랭킹 변동 로직 생략)
                            subtitleText = "$rankStr (확인됨)";
                            subtitleColor = Colors.blue;
                            trailingWidget = const Icon(Icons.new_releases_rounded, color: Colors.blue, 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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}