// packages/feature_common/lib/screens/ranking_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';

class RankingScreen extends StatefulWidget {
  // 🔽 [수정] 생성자에서 3개의 값을 주입받음
  final String gameType; // 'SUDOKU' 또는 'SPIDER'
  final List<GameDifficulty> difficulties; // 표시할 난이도 목록
  final String? initialDifficultyName; // 랭킹 버튼 클릭 시 전달된 초기값

  const RankingScreen({
    super.key,
    required this.gameType,
    required this.difficulties,
    this.initialDifficultyName,
  });

  @override
  State<RankingScreen> createState() => _RankingScreenState();
}

class _RankingScreenState extends State<RankingScreen> {
  final PuzzleService _puzzleService = PuzzleService();
  late Future<List<GameRankDto>> _rankingFuture;

  late String _selectedDifficultyName;

  @override
  void initState() {
    super.initState();
    // 🔽 [수정] 주입받은 난이도 목록(widget.difficulties)을 사용
    String defaultDifficultyName = widget.initialDifficultyName ?? widget.difficulties.first.name;

    if (!widget.difficulties.any((d) => d.name == defaultDifficultyName)) {
      defaultDifficultyName = widget.difficulties.first.name;
    }
    
    _fetchRanksForDifficulty(defaultDifficultyName);
  }

  void _fetchRanksForDifficulty(String difficultyName) {
    setState(() {
      _selectedDifficultyName = difficultyName;
      // 🔽 [수정] 선택된 이름으로 contextId를 찾음
      final String contextId = widget.difficulties
          .firstWhere((d) => d.name == difficultyName)
          .contextId;
      
      // 🔽 [수정] 주입받은 widget.gameType 사용
      _rankingFuture = _puzzleService.fetchRanks(widget.gameType, contextId);
    });
  }
  
  String _formatTime(int seconds) {
    final min = (seconds ~/ 60).toString().padLeft(2, '0');
    final sec = (seconds % 60).toString().padLeft(2, '0');
    return '$min:$sec';
  }

  String _formatScore(int? storedScore) {
    int score = 5 - (storedScore ?? 5);
    return 'SCORE: $score';
  }

  @override
  Widget build(BuildContext context) {
    context.watch<ThemeNotifier>();
    final theme = Theme.of(context);
    
    return Scaffold(
      appBar: AppBar(title: Text('${widget.gameType} 랭킹')),
      body: Column(
        children: [
          // 1. 난이도 선택 Dropdown
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: DropdownButton<String>(
              value: _selectedDifficultyName,
              isExpanded: true,
              // 🔽 [수정] 주입받은 widget.difficulties로 메뉴 생성
              items: widget.difficulties.map((level) {
                return DropdownMenuItem<String>(
                  value: level.name,
                  child: Text(level.name),
                );
              }).toList(),
              onChanged: (String? newValue) {
                if (newValue != null) {
                  _fetchRanksForDifficulty(newValue);
                }
              },
            ),
          ),
          // 2. 랭킹 리스트 (이하 build 로직은 원본과 동일)
          Expanded(
            child: FutureBuilder<List<GameRankDto>>(
              future: _rankingFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError) {
                  return Center(child: Text('랭킹 로딩 실패: ${snapshot.error}'));
                }
                if (!snapshot.hasData || snapshot.data!.isEmpty) {
                  return const Center(child: Text('등록된 랭킹이 없습니다.'));
                }

                final ranks = snapshot.data!;
                return ListView.builder(
                  itemCount: ranks.length,
                  itemBuilder: (context, index) {
                    final rank = ranks[index];
                    return ListTile(
                      leading: Text(
                        '${index + 1}.',
                        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      title: Text(rank.playerName, style: const TextStyle(fontSize: 18)),
                      trailing: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            _formatTime(rank.primaryScore),
                            style: TextStyle(
                              fontSize: 16, 
                              fontWeight: FontWeight.bold, 
                              color: theme.primaryColor
                            ),
                          ),
                          Text(
                            _formatScore(rank.secondaryScore),
                            style: TextStyle(
                              fontSize: 12, 
                              color: theme.textTheme.bodySmall?.color
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}