// 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';
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 = {};
  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('SPIDER');
    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<SpiderDifficulty>(
        gameType: 'SPIDER',
        myName: myName,
        allLevels: SpiderDifficulties.allDifficulties,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) {
        setState(() {
          _rankHistory = rankHistory;
        });
      }
    } catch (e) {
      log("SpiderLobbyScreen: 랭킹 확인 실패: $e");
    }
  }

  /// 🔽 [수정 없음] _startGame 메서드
  Future<void> _startGame(SpiderDifficulty 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;

    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(),
        ),
      ),
    );

    _loadProgress(forceRefreshRanks: false);
  }

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

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

    return CommonGameShell(
      title: '스파이더 솔리테어',
      onRankingPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'SPIDER',
              difficulties: SpiderDifficulties.allDifficulties,
              initialDifficultyName:
                  SpiderDifficulties.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: SpiderDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}