// packages/feature_game_spider/lib/screens/spider_lobby_screen.dart
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart'; // 👈 SessionNotifier 포함
import 'package:feature_common/feature_common.dart';
import 'spider_game_screen.dart';
import '../models/spider_difficulty.dart';
import '../controllers/spider_game_controller.dart'; 

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

class _SpiderLobbyScreenState extends State<SpiderLobbyScreen> {
  int _maxUnlockedLevel = 1; 
  Map<int, (int, int)> _rankHistory = {};
  // ❌ String? _userName; (SessionNotifier가 관리)
  bool _isLoading = false;
  
  // 🔽 [수정] SessionNotifier를 사용하기 위해 IdentityService 대신 추가
  late final SessionNotifier _sessionNotifier;
  final PuzzleService _puzzleService = PuzzleService();
  final IdentityService _identityService = IdentityService(); // 👈 (save/load progress를 위해 유지)

  @override
  void initState() {
    super.initState();
    // 🔽 [수정] initState에서 SessionNotifier를 read
    // SessionNotifier의 loadSession()이 먼저 완료되었다고 가정
    _sessionNotifier = context.read<SessionNotifier>();
    
    // 🔽 [수정] _loadProgress가 랭킹까지 모두 새로고침 (최초 1회)
    _loadProgress(forceRefreshRanks: true);
  }

  /// 🔽 [수정] _loadProgress 메서드 (SessionNotifier 사용 및 로직 분리)
  Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
    // 1. (가벼움) 레벨 정보 새로고침
    final maxLevel = await _identityService.getMaxUnlockedLevel(gameType: 'SPIDER');
    if (mounted) { 
      setState(() { 
        _maxUnlockedLevel = maxLevel; 
      }); 
    }

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

    // 🔽 [수정] _sessionNotifier에서 유저 이름을 가져옴
    final String? myName = _sessionNotifier.session?.userName;
    if (myName == null) return; // 게스트이거나 아직 이름 저장을 안 함

    try {
      final Map<int, int> oldRankMap = await _identityService.getLastSavedRankMap(gameType: 'SPIDER');
      List<Future<List<GameRankDto>>> rankFutures = [];
      for (final level in SpiderDifficulties.allDifficulties) {
        rankFutures.add(_puzzleService.fetchRanks('SPIDER', level.contextId));
      }
      final List<List<GameRankDto>> allRankResults = await Future.wait(rankFutures);
      Map<int, int> newRankMapForStorage = {};
      Map<int, (int, int)> newRankHistoryForState = {};
      for (int i = 0; i < SpiderDifficulties.allDifficulties.length; i++) {
        final level = SpiderDifficulties.allDifficulties[i];
        final currentRanks = allRankResults[i];
        final int levelIndex = level.levelIndex;
        final int oldRank = oldRankMap[levelIndex] ?? 0;
        int currentRank = 0;
        int myRankIndex = currentRanks.indexWhere((r) => r.playerName == myName);
        if (myRankIndex != -1) { currentRank = myRankIndex + 1; }
        newRankMapForStorage[levelIndex] = currentRank;
        newRankHistoryForState[levelIndex] = (oldRank, currentRank);
      }
      await _identityService.saveLastRankMap(newRankMapForStorage, gameType: 'SPIDER');
      if (mounted) { setState(() { _rankHistory = newRankHistoryForState; }); }
      log("스파이더 랭킹 변동 확인 완료. (유저: $myName)");
    } catch (e) {
      log("SpiderLobbyScreen: 랭킹 확인 실패: $e");
    }
  }


  /// 🔽 [수정] _startGame 메서드 (SessionNotifier 사용)
  Future<void> _startGame(SpiderDifficulty level) async {
    setState(() { _isLoading = true; });

    // 1. [수정] SessionNotifier에서 유저 정보 가져오기
    final session = _sessionNotifier.session;
    if (session == null) {
      log("세션이 로드되지 않아 게임을 시작할 수 없습니다.");
      setState(() { _isLoading = false; });
      return;
    }
    
    final String userId = session.userId;
    final String? userName = session.userName;

    // 2. 컨트롤러 생성 및 새 게임 시작
    final gameController = SpiderGameController();
    gameController.setUserInfo(userId, userName); // 👈 유저 정보 주입
    gameController.startNewGame(level);

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

    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => 
          ChangeNotifierProvider.value(
            value: gameController,
            child: const SpiderGameScreen(),
          ),
      ),
    );
    
    // 🔽 [핵심 수정]
    // 랭킹(forceRefreshRanks: true)은 새로고침하지 않고,
    // 레벨 잠금 상태(forceRefreshRanks: false)만 새로고침합니다.
    _loadProgress(forceRefreshRanks: false);
  }

  @override
  Widget build(BuildContext context) {
    // 🔽 [수정] ThemeNotifier와 SessionNotifier를 모두 watch
    context.watch<ThemeNotifier>();
    context.watch<SessionNotifier>(); // 👈 세션 변경(로그인/로그아웃) 감지
    
    final bool allLevelsUnlocked = _maxUnlockedLevel >= 9;
    final theme = Theme.of(context);

    return CommonGameShell(
      title: '스파이더 솔리테어',
      onRankingPressed: () {
        // ... (랭킹 버튼 로직 동일)
      },
      // 🔽 [수정] RefreshIndicator 추가 (당겨서 랭킹 새로고침)
      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: SpiderDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          // ... (이하 ListTile 로직은 모두 동일)
                          final SpiderDifficulty level = SpiderDifficulties.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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}