// packages/feature_game_sudoku/lib/screens/sudoku_lobby_screen.dart
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// [C] 서비스 import
import 'package:service_api/service_api.dart';
// [A] 공통 셸(Shell) 위젯 import
import 'package:feature_common/feature_common.dart';
// [B] 같은 패키지 내의 화면/모델 import
import 'game_screen.dart';
import '../models/game_level.dart';

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

  @override
  State<SudokuLobbyScreen> createState() => _SudokuLobbyScreenState();
}

class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
  int _maxUnlockedLevel = 1;
  Map<int, (int, int)> _rankHistory = {};
  late String _selectedThemeName;
  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();
    _selectedThemeName = AppThemes.random;
    _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('SUDOKU');
    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<GameLevel>(
        gameType: 'SUDOKU',
        myName: myName,
        allLevels: AppLevels.allLevels,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) {
        setState(() {
          _rankHistory = rankHistory;
        });
      }
    } catch (e) {
      log("SudokuLobbyScreen: 랭킹 확인 실패: $e");
    }
  }

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

    try {
      final session = _sessionNotifier.session;
      if (session == null) {
        throw Exception("세션이 로드되지 않았습니다.");
      }
      
      final String difficulty = level.levelIndex.toString();
      // [🔥 수정] _puzzleService 인스턴스 사용
      final SudokuGameDto gameData = await _puzzleService.startGame(difficulty);

      final String userId = session.userId;
      final String? userName = session.userName;

      if (mounted) {
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GameScreen(
              gameData: gameData,
              themeName: _selectedThemeName,
              userId: userId,
              userName: userName,
              levelIndex: level.levelIndex,
            ),
          ),
        );

        _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 >= 99;
    final theme = Theme.of(context);

    return CommonGameShell(
      title: '스도쿠 게임',
      onRankingPressed: () {
        // [🔥 수정] GameLevel이 GameDifficulty를 상속하므로 변환(map) 불필요
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'SUDOKU',
              difficulties: AppLevels.allLevels, // 👈 [수정]
              initialDifficultyName: AppLevels.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: [
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 20.0, vertical: 10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text("테마: ", style: TextStyle(fontSize: 18)),
                        DropdownButton<String>(
                          value: _selectedThemeName,
                          items:
                              AppThemes.selectableThemeNames.map((themeName) {
                            return DropdownMenuItem<String>(
                              value: themeName,
                              child:
                                  Text(themeName, style: const TextStyle(fontSize: 20)),
                            );
                          }).toList(),
                          onChanged: (themeName) {
                            if (themeName != null) {
                              setState(() {
                                _selectedThemeName = themeName;
                              });
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: RefreshIndicator(
                      onRefresh: () => _loadProgress(forceRefreshRanks: true),
                      child: ListView.builder(
                        itemCount: AppLevels.allLevels.length,
                        itemBuilder: (context, index) {
                          final GameLevel level = AppLevels.allLevels[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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}