// packages/feature_game_sequence/lib/screens/sequence_lobby_screen.dart

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// [C] 공통 서비스
import 'package:service_api/service_api.dart';
// [A] 공통 UI 셸
import 'package:feature_common/feature_common.dart';
// [B] 순서 기억 게임 모델/컨트롤러
import '../models/sequence_models.dart';
import 'sequence_game_screen.dart';
import '../controllers/sequence_game_controller.dart';

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

class _SequenceLobbyScreenState extends State<SequenceLobbyScreen> {
  int _maxUnlockedLevel = 1; 
  Map<int, (int, int)> _rankHistory = {};
  bool _isLoading = false;
  
  // 🔽 공통 서비스 인스턴스 (직접 생성)
  late final SessionNotifier _sessionNotifier;
  late final LobbyHelperService _lobbyHelper;
  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('SEQUENCE');
    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<SequenceDifficulty>(
        gameType: 'SEQUENCE',
        myName: myName,
        allLevels: SequenceDifficulties.allDifficulties,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) { setState(() { _rankHistory = rankHistory; }); }
      log("순서 기억 랭킹 변동 확인 완료. (유저: $myName)");
    } catch (e) {
      log("SequenceLobbyScreen: 랭킹 확인 실패: $e");
    }
  }


  /// 🔽 [게임 시작] 컨트롤러 생성 및 화면 이동
  Future<void> _startGame(SequenceDifficulty 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 = SequenceGameController();
    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 SequenceGameScreen(),
          ),
      ),
    );
    
    // 3. 게임 종료 후 레벨 잠금 상태만 새로고침
    _loadProgress(forceRefreshRanks: false);
  }

  @override
  Widget build(BuildContext context) {
    context.watch<ThemeNotifier>();
    context.watch<SessionNotifier>();
    
    final bool allLevelsUnlocked = _maxUnlockedLevel >= SequenceDifficulties.allDifficulties.length;
    final theme = Theme.of(context);
    
    // 🔽 [핵심] CommonGameShell 사용
    return CommonGameShell(
      title: '순서 기억 퀴즈 (Simon)',
      onRankingPressed: () {
        // 랭킹 화면 호출
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'SEQUENCE',
              difficulties: SequenceDifficulties.allDifficulties, // 👈 [수정] 바로 전달
              initialDifficultyName: SequenceDifficulties.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: SequenceDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          final SequenceDifficulty level = SequenceDifficulties.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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}