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/finddiff_models.dart';
import '../controllers/finddiff_controller.dart';
import 'finddiff_game_screen.dart';

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

  @override
  State<FindDiffLobbyScreen> createState() => _FindDiffLobbyScreenState();
}

class _FindDiffLobbyScreenState extends State<FindDiffLobbyScreen> {
  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. 최대 레벨 로드 ('FIND_DIFF' 키 사용)
    final maxLevel = await _lobbyHelper.loadMaxLevel('FIND_DIFF');
    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<FindDiffDifficulty>(
        gameType: 'FIND_DIFF',
        myName: myName,
        allLevels: FindDiffDifficulties.allDifficulties,
        getLevelIndex: (level) => level.levelIndex,
      );
      if (mounted) {
        setState(() {
          _rankHistory = rankHistory;
        });
      }
    } catch (e) {
      log("FindDiffLobbyScreen: 랭킹 확인 실패: $e");
    }
  }

  /// [게임 시작] 컨트롤러 생성 및 화면 이동
  Future<void> _startGame(FindDiffDifficulty 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 = FindDiffController();
    gameController.setUserInfo(userId, userName);
    gameController.startNewGame(level);

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

    // 2. 게임 화면으로 이동
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChangeNotifierProvider.value(
          value: gameController,
          child: const FindDiffGameScreen(),
        ),
      ),
    );

    // 3. 복귀 후 레벨 상태 갱신
    _loadProgress(forceRefreshRanks: false);
  }

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

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

    return CommonGameShell(
      title: '다른 그림 찾기',
      onRankingPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => RankingScreen(
              gameType: 'FIND_DIFF',
              difficulties: FindDiffDifficulties.allDifficulties,
              initialDifficultyName:
                  FindDiffDifficulties.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: FindDiffDifficulties.allDifficulties.length,
                        itemBuilder: (context, index) {
                          final FindDiffDifficulty level =
                              FindDiffDifficulties.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,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}