import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';
import '../../dialogs/room_setting_finish_dialog.dart';
import '../../dialogs/user_info_finish_dialog.dart';

import '../../config/config.dart';

import 'main_page.dart';

class FinishTeamPage extends StatefulWidget {
  final int roomSeq;
  final String enterType; // from waiting/ongoing (대기/진행중) → when back, go to MainPage

  const FinishTeamPage({
    Key? key,
    required this.roomSeq,
    required this.enterType,
  }) : super(key: key);

  @override
  State<FinishTeamPage> createState() => _FinishTeamPageState();
}

class _FinishTeamPageState extends State<FinishTeamPage> {
  bool _isLoading = true;

  Map<String, dynamic> _roomInfo = {};
  Map<String, dynamic> _userMap = {};
  List<Map<String, dynamic>> _userList = [];

  String _roomTitle = '';
  String _masterUserSeq = '0';
  DateTime? _startDt;
  DateTime? _endDt;

  // Teams and their members (팀별 [ { user }, { user } ... ])
  Map<String, List<Map<String, dynamic>>> _teamMap = {};
  // Scores by team (팀별 점수)
  Map<String, int> _teamScoreMap = {};

  @override
  void initState() {
    super.initState();
    _fetchFinishRoomInfo();
  }

  Future<void> _fetchFinishRoomInfo() async {
    setState(() => _isLoading = true);
    try {
      final body = {"room_seq": "${widget.roomSeq}"};
      final response = await Api.serverRequest(
        uri: '/room/score/get/finish/room/info',
        body: body,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          final data  = resp['data'] ?? {};
          final rInfo = data['room_info'] ?? {};
          final List<dynamic> uInfoList = data['user_info'] ?? [];

          final rTitle = (rInfo['room_title'] ?? '') as String;
          final mSeq   = (rInfo['master_user_seq'] ?? 0) as int;
          final sdt    = rInfo['start_dt'];
          final edt    = rInfo['end_dt'];

          setState(() {
            _roomInfo      = rInfo;
            _roomTitle     = rTitle.isNotEmpty ? rTitle : 'Finished Team Game';
            _masterUserSeq = mSeq.toString();

            if (sdt != null && sdt is String && sdt.contains('T')) {
              _startDt = DateTime.tryParse(sdt);
            }
            if (edt != null && edt is String && edt.contains('T')) {
              _endDt = DateTime.tryParse(edt);
            }
          });

          // user_info 처리 (List)
          final List<Map<String, dynamic>> tempList = [];
          for (var u in uInfoList) {
            tempList.add(Map<String, dynamic>.from(u));
          }

          // 전체 플레이어
          final players = tempList.toList();

          // (3) Separate by team + sum scores (팀명별 분류 + 점수 합)
          final Map<String, List<Map<String, dynamic>>> tMap = {};
          final Map<String, int> tScoreMap = {};

          for (var user in players) {
            final tName = (user['team_name'] ?? 'WAIT').toString().toUpperCase();
            if (tName == 'WAIT') continue; 
            tMap.putIfAbsent(tName, () => []);
            tMap[tName]!.add(user);
          }

          // 팀별 점수 계산
          tMap.forEach((team, mems) {
            int sumScore = 0;
            // 팀 멤버를 점수 내림차순 정렬
            mems.sort((a, b) {
              final sa = (a['score'] ?? 0) as int;
              final sb = (b['score'] ?? 0) as int;
              return sb.compareTo(sa);
            });
            for (var m in mems) {
              sumScore += (m['score'] ?? 0) as int;
            }
            tScoreMap[team] = sumScore;
          });

          // (4) 팀들을 점수 순으로 정렬
          final sortedTeams = tScoreMap.keys.toList();
          sortedTeams.sort((a, b) => tScoreMap[b]!.compareTo(tScoreMap[a]!));

          final Map<String, List<Map<String, dynamic>>> finalTeamMap = {};
          final Map<String, int> finalScoreMap = {};

          for (var t in sortedTeams) {
            finalTeamMap[t] = tMap[t]!;
            finalScoreMap[t] = tScoreMap[t]!;
          }

          setState(() {
            _userList      = tempList; // 전체 유저 리스트
            _teamMap       = finalTeamMap;
            _teamScoreMap  = finalScoreMap;
            _isLoading     = false;
          });
        } else {
          final msgTitle   = resp['response_info']?['msg_title'] ?? 'Error';
          final msgContent = resp['response_info']?['msg_content'] ?? 'Failed to fetch data';
          showResponseDialog(context, msgTitle, msgContent);
        }
      } else {
        showResponseDialog(context, 'Failed', 'Server communication error.');
      }
    } catch (e) {
      showResponseDialog(context, 'Error', '$e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<bool> _onWillPop() async {
    if (widget.enterType == 'game') {
      // If from game, go to main (대기/진행중에서 왔으면 메인으로)
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const MainPage()), (route) => false);
    } else {
      // Otherwise just pop
      Navigator.pop(context);
    }
    return false;
  }

  Future<void> _openRoomSettingDialog() async {
    if (_roomInfo.isEmpty) return;
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => RoomSettingFinishDialog(roomInfo: _roomInfo),
    );
  }

  Widget _buildGameTimeWidget() {
    if (_startDt == null || _endDt == null) {
      return const Text('Game duration: 00:00', // '게임 진행 시간: 00:00'
          style: TextStyle(fontSize: 14));
    }
    final dur = _endDt!.difference(_startDt!);
    final hh = dur.inHours.toString().padLeft(2, '0');
    final mm = dur.inMinutes.remainder(60).toString().padLeft(2, '0');
    return Text('Game duration: $hh:$mm',  // '게임 진행 시간: $hh:$mm'
        style: const TextStyle(fontSize: 14));
  }

  /// Team box (팀 박스: e.g. 1st, 2nd, 3rd with gold/silver/bronze background)
  Widget _buildTeamBox(String teamName, int index) {
    final members = _teamMap[teamName] ?? [];
    final tScore  = _teamScoreMap[teamName] ?? 0;

    // 1st/2nd/3rd team color
    Color bgColor = Colors.white;
    if (index == 0) {
      bgColor = const Color(0xFFFFF9C4); // Goldish
    } else if (index == 1) {
      bgColor = const Color(0xFFE0E0E0); // Silverish
    } else if (index == 2) {
      bgColor = const Color(0xFFFFE0B2); // Bronzy
    }

    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        color: bgColor,
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          // Header bar (상단 바)
          Container(
            color: Colors.black,
            width: double.infinity,
            padding: const EdgeInsets.all(8),
            child: Center(
              child: Text(
                '$teamName Team (Score: $tScore)', 
                // '$teamName 팀 (점수: $tScore)'
                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          // Team members (팀 멤버)
          Container(
            padding: const EdgeInsets.all(8),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: members.map((m) => _buildTeamMember(m)).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Team member display (팀 멤버 표시)
  Widget _buildTeamMember(Map<String, dynamic> user) {
    final score      = (user['score'] ?? 0) as int;
    var nickname     = user['nickname'] ?? 'User'; // '유저'
    final profileImg = user['profile_img'] ?? '';
    final userSeq    = user['user_seq'].toString() ?? '0';
    final participantType = user['participant_type'] ?? '';

    // Mark room master (방장 표시)
    if (_masterUserSeq == userSeq) {
      nickname = '★' + nickname;
    } else if (participantType == 'ADMIN') {
      // Admin
      nickname = '☆' + nickname;
    }

    return GestureDetector(
      onTap: () => _onTapUser(user),
      child: Container(
        width: 60,
        margin: const EdgeInsets.only(right: 8),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('$score', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            const SizedBox(height: 2),
            Container(
              width: 30, 
              height: 30,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.black),
              ),
              child: ClipOval(
                child: Image.network(
                  '${Config.baseUrl}/images$profileImg',
                  fit: BoxFit.cover,
                  errorBuilder: (ctx, err, st) => const Center(
                    child: Text('ERR', style: TextStyle(fontSize: 8)),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 2),
            Text(
              nickname,
              style: const TextStyle(fontSize: 11),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _onTapUser(Map<String, dynamic> userData) async {
    // Show user info dialog (유저 정보 모달)
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => UserInfoFinishDialog(userData: userData),
    );
  }

  @override
  Widget build(BuildContext context) {
    final teamNames = _teamMap.keys.toList(); 
    // Already sorted by score (이미 점수순 정렬됨)

    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.black,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: _onWillPop,
          ),
          title: Text(_roomTitle, style: const TextStyle(color: Colors.white)),
        ),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    // Room info + time (방 정보 + 시간)
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ElevatedButton(
                          onPressed: _openRoomSettingDialog,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.white,
                            side: const BorderSide(color: Colors.black),
                          ),
                          child: const Text(
                            'View Room Info', 
                            // '방 정보 보기'
                            style: TextStyle(color: Colors.black),
                          ),
                        ),
                        _buildGameTimeWidget(),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // Team boxes (팀 박스들)
                    for (int i = 0; i < teamNames.length; i++)
                      _buildTeamBox(teamNames[i], i),
                  ],
                ),
              ),
      ),
    );
  }
}
