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 FinishPrivatePage extends StatefulWidget {
  final int roomSeq;
  final String enterType; // from waiting/ongoing => if back, go to MainPage (대기/진행중에서 넘어온 경우 => 뒤로가기 시 메인으로)

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

  @override
  State<FinishPrivatePage> createState() => _FinishPrivatePageState();
}

class _FinishPrivatePageState extends State<FinishPrivatePage> {
  bool _isLoading = true;

  Map<String, dynamic> _roomInfo = {}; // room_info from server (서버에서 받은 room_info)
  // Entire user_info Map (전체 user_info)
  //   userSeq → { user_seq, nickname, participant_type, score, ... }
  Map<String, dynamic> _userMap = {};

  // Participant list in descending score order (점수 내림차순 참가자 목록)
  List<Map<String, dynamic>> _playerList = [];

  String _roomTitle = '';
  DateTime? _startDt;
  DateTime? _endDt;
  String _masterUserSeq = '0'; // room master user_seq (방장 user_seq)

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

  /// (A) Fetch finished room info from server (서버에서 종료된 방 정보를 가져옴)
  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'] ?? {};

          // (1) room_info
          final rInfo = data['room_info'] ?? {};

          // (2) user_info는 List 형태로 받아오기
          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 Room (Solo)'; 
            _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);
            }
          });

          // (3) List로 변환
          final List<Map<String, dynamic>> tempList = [];
          for (var item in uInfoList) {
            tempList.add(Map<String, dynamic>.from(item));
          }

          // (4) 점수 내림차순 정렬
          tempList.sort((a, b) {
            final sa = (a['score'] ?? 0) as int;
            final sb = (b['score'] ?? 0) as int;
            return sb.compareTo(sa);
          });

          // (5) 상태 갱신
          setState(() {
            _playerList = tempList;
            _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);
    }
  }

  /// (B) Back press (뒤로가기)
  Future<bool> _onWillPop() async {
    if (widget.enterType == 'game') {
      // If from an ongoing game → go to main (진행중에서 넘어왔으면 => 메인으로)
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const MainPage()), (route) => false);
    } else {
      // If from search, etc. → just pop (검색 등에서 왔으면 => pop)
      Navigator.pop(context);
    }
    return false;
  }

  /// (C) Show room info modal (rooms setting finish dialog: read only) 
  ///     (방 정보보기 모달: 읽기 전용)
  Future<void> _openRoomSettingDialog() async {
    if (_roomInfo.isEmpty) return;
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => RoomSettingFinishDialog(roomInfo: _roomInfo),
    );
  }

  /// (D) Show game duration (게임 진행 시간 표시)
  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),
    );
  }

  /// (E) Build player list item (점수 내림차순)
  ///  - 1st/2nd/3rd => gold/silver/bronze medal
  Widget _buildPlayerItem(Map<String, dynamic> user, int index) {
    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'] ?? '';

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

    // Medal icons
    Widget medal = const SizedBox();
    if (index == 0) {
      medal = const Text('🥇 ', style: TextStyle(fontSize: 16));
    } else if (index == 1) {
      medal = const Text('🥈 ', style: TextStyle(fontSize: 16));
    } else if (index == 2) {
      medal = const Text('🥉 ', style: TextStyle(fontSize: 16));
    }

    return GestureDetector(
      onTap: () => _onTapUser(user),
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            medal,
            // Profile
            Container(
              width: 36, 
              height: 36,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.black54),
              ),
              child: ClipOval(
                child: (profileImg.isNotEmpty)
                    ? Image.network(
                        '${Config.baseUrl}/images$profileImg',
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => const Center(child: Text('ERR')),
                      )
                    : const Center(
                        child: Text(
                          'No\nImg', 
                          // '이미지 없음'
                          textAlign: TextAlign.center, 
                          style: TextStyle(fontSize: 10),
                        ),
                      ),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                nickname,
                style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
            Text('$score pt', // '$score 점'
                style: const TextStyle(fontSize: 14)),
          ],
        ),
      ),
    );
  }

  /// User click → user info finish dialog (사용자 클릭 -> 새 유저 정보 모달)
  Future<void> _onTapUser(Map<String, dynamic> userData) async {
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => UserInfoFinishDialog(userData: userData),
    );
  }

  @override
  Widget build(BuildContext context) {
    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: [
                    // (A) Top: [View Room Info] button + game duration
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ElevatedButton(
                          onPressed: _openRoomSettingDialog,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.white,
                            side: const BorderSide(color: Colors.black, width: 1),
                          ),
                          child: const Text(
                            'View Room Info', // '방 정보 보기'
                            style: TextStyle(color: Colors.black),
                          ),
                        ),
                        _buildGameTimeWidget(),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // (C) player list (참가자 목록)
                    ListView.builder(
                      primary: false,
                      shrinkWrap: true,
                      itemCount: _playerList.length,
                      itemBuilder: (ctx, i) => _buildPlayerItem(_playerList[i], i),
                    ),
                  ],
                ),
              ),
      ),
    );
  }
}
