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

import 'main_page.dart';
import 'finish_team_page.dart';  // 팀전 종료 화면
import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';
import '../../dialogs/score_edit_dialog.dart';
import '../../dialogs/user_info_basic_dialog.dart';
import '../../plugins/admob.dart';
import '../../config/config.dart';

class PlayingTeamPage extends StatefulWidget {
  final int roomSeq;
  final String roomTitle;

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

  @override
  State<PlayingTeamPage> createState() => _PlayingTeamPageState();
}

class _PlayingTeamPageState extends State<PlayingTeamPage> {
  // Firebase Realtime Database (FRD)
  late DatabaseReference _roomRef;
  Stream<DatabaseEvent>? _roomStream;
  StreamSubscription<DatabaseEvent>? _roomStreamSubscription;

  // ─────────────────────────────────────────
  // One-hour countdown (운영시간 카운트다운)
  // ─────────────────────────────────────────
  Timer? _countdownTimer;
  Duration _remaining = const Duration(hours: 1); // 기본 1시간
  DateTime? _roomStartDt; // roomInfo.room_start_dt
  String _roomRunningTime = '0'; 
  bool _roomTimeOut = false;
  String _roomExitYn = 'N';

  String roomMasterYn = 'N'; // 방장 여부
  String roomTitle = '';

  int myScore = 0;
  int myTeamScore = 0;

  Map<String, int> _teamScoreMap = {};  
  Map<String, List<Map<String, dynamic>>> _teamMap = {}; 

  bool _isLoading = true;
  bool _movedToFinishPage = false; // 종료 페이지 이동 중복 방지

  String mySeq = '0';

  // userListMap: { seq: true/false }
  Map<String, bool> _userListMap = {};

  // 나의 참가 타입
  String myParticipantType = 'PLAYER';

  // 점수 공개 범위
  String scoreOpenRange = 'ALL';

  @override
  void initState() {
    super.initState();
    // (1) Restore FRD connection (FRD 연결 복원)
    FirebaseDatabase.instance.goOnline();

    roomTitle = widget.roomTitle;
    // (D) Initialize room info (방 정보 초기화)
    _initFirebase();
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _roomStreamSubscription?.cancel();
    super.dispose();
  }

  Future<void> _initFirebase() async {
    final prefs = await SharedPreferences.getInstance();
    mySeq = prefs.getInt('my_user_seq')?.toString() ?? '0';

    final roomKey = 'korea-${widget.roomSeq}';
    _roomRef = FirebaseDatabase.instance.ref('rooms/$roomKey');

    _listenRoomData();
  }

  void _listenRoomData() {
    _roomStream = _roomRef.onValue;
    _roomStream?.listen((event) {
      final snapshot = event.snapshot;
      if (!snapshot.exists) {
        setState(() {
          _isLoading = false;
          roomTitle = 'No Room Info'; // '방 정보 없음'
          myScore = 0;
          myTeamScore = 0;
          _teamScoreMap = {};
          _teamMap = {};
        });
        return;
      }

      final data = snapshot.value as Map<dynamic, dynamic>? ?? {};
      final roomInfoData = data['roomInfo'] as Map<dynamic, dynamic>? ?? {};
      final userInfoData = data['userInfo'] as Map<dynamic, dynamic>? ?? {};
      final userListData = data['userList'] as Map<dynamic, dynamic>? ?? {};

      final roomStatus = (roomInfoData['room_status'] ?? 'WAIT').toString().toUpperCase();
      if (roomStatus == 'FINISH') {
        // If finished, move to finish screen (종료화면)
        if (mounted) {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (_) => FinishTeamPage(roomSeq: widget.roomSeq, enterType: 'game')),
            (route) => false,
          );
        }
        return;
      }

      setState(() {
        // Room running time (운영시간)
        _roomRunningTime = roomInfoData['running_time'] ?? '0';

        // Score open range (점수 공개 범위)
        scoreOpenRange = roomInfoData['score_open_range'] ?? 'ALL';

        final masterSeq = roomInfoData['master_user_seq'];
        roomMasterYn = (masterSeq != null && masterSeq.toString() == mySeq) ? 'Y' : 'N';

        final newTitle = (roomInfoData['room_title'] ?? '') as String;
        if (newTitle.isNotEmpty) roomTitle = newTitle;

        _userListMap.clear();
        if (userListData != null) {
          userListData.forEach((k, v) {
            _userListMap[k.toString().replaceAll('_', '')] = (v == true);
          });
        }

        // Create raw user list (전체 유저 목록)
        final List<Map<String, dynamic>> rawList = [];
        userInfoData.forEach((uSeq, uData) {
          uSeq = uSeq.toString().replaceAll('_', '');
          // Mark room master
          if (uSeq.toString() == roomInfoData['master_user_seq'].toString()) {
            // 방장 표시
            uData['nickname'] = '★' + (uData['nickname'] ?? 'User');
          } else if ((uData['participant_type'] ?? '').toString().toUpperCase() == 'ADMIN') {
            // 관리자(사회자) 표시
            uData['nickname'] = '☆' + (uData['nickname'] ?? 'User');
          }
          rawList.add({
            'user_seq': uSeq,
            'participant_type': (uData['participant_type'] ?? '').toString().toUpperCase(),
            'nickname': uData['nickname'] ?? 'User', // '유저'
            'team_name': (uData['team_name'] ?? '').toString().toUpperCase(),
            'score': uData['score'] ?? 0,
            'profile_img': uData['profile_img'] ?? '',
          });
          if (uSeq.toString() == mySeq) {
            myParticipantType = (uData['participant_type'] ?? '').toString().toUpperCase();
          }
        });

        // My score & team score (내 점수 & 팀 점수)
        int tmpMyScore = 0;
        int tmpMyTeamScore = 0;
        String myTeam = 'WAIT';

        for (var user in rawList) {
          final uSeq = user['user_seq'].toString();
          final sc   = (user['score'] ?? 0) as int;
          final tName= (user['team_name'] ?? 'WAIT');
          if (uSeq == mySeq) {
            tmpMyScore = sc;
            myTeam = tName;
          }
        }

        for (var user in rawList) {
          final tName = (user['team_name'] ?? 'WAIT');
          final sc    = (user['score'] ?? 0) as int;
          if (tName == myTeam && myTeam != 'WAIT') {
            tmpMyTeamScore += sc;
          }
        }

        // Build team map excluding ADMIN, WAIT (ADMIN, WAIT 제외)
        final Map<String, List<Map<String, dynamic>>> tMap = {};
        final Map<String, int> tScoreMap = {};

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

        // Calculate team score (팀 스코어 계산)
        tMap.forEach((k, members) {
          int sumScore = 0;
          for (var m in members) {
            sumScore += (m['score'] ?? 0) as int;
          }
          tScoreMap[k] = sumScore;
        });

        myScore = tmpMyScore;
        myTeamScore = tmpMyTeamScore;
        _teamMap = tMap;
        _teamScoreMap = tScoreMap;

        _isLoading = false;
      });

      // If FINISH => move to finish page
      if (roomStatus == 'FINISH' && !_movedToFinishPage) {
        _movedToFinishPage = true;
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(
            builder: (_) => FinishTeamPage(
              roomSeq: widget.roomSeq,
              enterType: 'game',
            ),
          ),
          (route) => false,
        );
        return;
      }

      // Parse room_start_dt for countdown (운영시간 카운트다운)
      final roomStartDtStr = (roomInfoData['start_dt'] ?? '') as String;
      if (roomStartDtStr.isNotEmpty) {
        final dt = DateTime.tryParse(roomStartDtStr);
        if (dt != null) {
          setState(() {
            _roomStartDt = dt;
          });
          _startCountdownTimer();
        }
      }
    }, onError: (err) {
      setState(() {
        _isLoading = false;
        roomTitle = 'Error occurred'; // '오류 발생'
      });
    });
  }

  // Countdown timer for running time (운영시간 카운트다운 타이머)
  void _startCountdownTimer() {
    if (_countdownTimer != null && _countdownTimer!.isActive) {
      return; 
    }
    if (_roomStartDt == null) return;

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // End time = roomStartDt + running time (roomStartDt + 운영시간)
      final endTime = _roomStartDt!.add(Duration(hours: int.parse(_roomRunningTime)));
      final now = DateTime.now();
      final diff = endTime.difference(now);

      if (diff.isNegative) {
        // Time's up -> auto finish
        timer.cancel();
        _remaining = const Duration(seconds: 0);
        _onAutoTimeout();
      } else {
        setState(() {
          _remaining = diff;
        });
      }
    });
  }

  // Auto finish when time is up (운영시간 만료 후 자동 종료)
  void _onAutoTimeout() {
    setState(() {
      _roomTimeOut = true;
      _roomExitYn = 'Y';
    });
    _requestFinish();
  }

  /// Request finish the game (게임종료)
  Future<void> _requestFinish() async {
    final body = {
      "room_seq": "${widget.roomSeq}",
      "room_type": "TEAM",
    };
    try {
      await Api.serverRequest(uri: '/room/score/game/finish', body: body);
    } catch (e) {
      // ignore
    }
  }

  // On pressing back (뒤로가기)
  Future<bool> _onWillPop() async {
    if (roomMasterYn == 'Y') {
      // If master, prompt (방장 모달)
      final confirm = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
              side: const BorderSide(color: Colors.black, width: 1),
            ),
            title: const Text(
              'Leave',   // '나가기'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            content: const Text(
              'If the master leaves, the game will end.\nAre you sure you want to leave?', 
              // '방장이 나가면 게임이 종료됩니다.\n정말 나가시겠습니까?'
              style: TextStyle(fontSize: 14),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                ),
                child: const Text('Cancel'), // '취소'
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                ),
                child: const Text('End'), // '종료'
              ),
            ],
          );
        },
      );
      if (confirm != true) return false;

      await _requestFinish();
    } else {
      // If not master (일반 유저)
      final confirm = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
              side: const BorderSide(color: Colors.black, width: 1),
            ),
            title: const Text(
              'Leave', // '나가기'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            content: const Text(
              'If you leave this ongoing game, you cannot rejoin.\nAre you sure you want to leave?', 
              // '진행중인 방에서 나가면 재입장이 불가능합니다.\n정말 나가시겠습니까?'
              style: TextStyle(fontSize: 14),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                ),
                child: const Text('Cancel'), // '취소'
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                style: TextButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                ),
                child: const Text('Leave'), // '나가기'
              ),
            ],
          );
        },
      );
      if (confirm != true) return false;
    }

    // userList => false
    final userRef = _roomRef.child('userList').child('_$mySeq');
    await userRef.set(false);

    if (!mounted) return false;
    Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const MainPage()), (route) => false);
    return false;
  }

  // Format countdown (카운트다운 표시용)
  String _formatDuration(Duration d) {
    final hh = d.inHours.toString().padLeft(2, '0');
    final mm = d.inMinutes.remainder(60).toString().padLeft(2, '0');
    final ss = d.inSeconds.remainder(60).toString().padLeft(2, '0');
    return '$hh:$mm:$ss';
  }

  @override
  Widget build(BuildContext context) {
    final countdownStr = _formatDuration(_remaining);

    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // Left: room title (방 제목)
              Expanded(
                child: Text(
                  roomTitle.isNotEmpty ? roomTitle : 'Room Title', // '방 제목'
                  style: const TextStyle(color: Colors.white),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(width: 4),
              // Right: countdown (남은시간)
              Text(
                countdownStr, // e.g. "10:23"
                style: const TextStyle(color: Colors.white),
              ),
            ],
          ),
          backgroundColor: Colors.black,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: () => _onWillPop(),
          ),
          actions: [
            if (roomMasterYn == 'Y')
              TextButton(
                onPressed: _requestFinish,
                child: const Text(
                  'End Game', // '게임종료'
                  style: TextStyle(color: Colors.white),
                ),
              ),
          ],
        ),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  // (A) My score / my team's score (내 점수 / 우리 팀 점수)
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(top: 16, bottom: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Column(
                          children: [
                            const Text(
                              'My Score', // '내 점수'
                              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '$myScore',
                              style: const TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                        Container(width: 1, height: 60, color: Colors.black),
                        Column(
                          children: [
                            const Text(
                              'Team Score', // '우리 팀 점수'
                              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '$myTeamScore',
                              style: const TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  const Divider(height: 1, color: Colors.black),

                  // (B) Teams section (팀별 표시)
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(8),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: _teamMap.keys.map(_buildTeamSection).toList(),
                      ),
                    ),
                  ),
                ],
              ),
        bottomNavigationBar: AdBannerWidget(),
      ),
    );
  }

  Widget _buildTeamSection(String teamName) {
    final upperName = teamName.toUpperCase();
    final members = _teamMap[upperName] ?? [];
    final tempTeamScore = _teamScoreMap[upperName] ?? 0;

    // If scoreOpenRange == 'TEAM' or 'ALL', show team score, else '-'
    final teamScore = (scoreOpenRange == 'TEAM' || scoreOpenRange == 'ALL') ? tempTeamScore : '-';

    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            color: Colors.black,
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Center(
              child: Text(
                '$teamName (Team Score $teamScore)', // '$teamName (팀점수 $teamScore)'
                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(children: members.map(_buildTeamMemberItem).toList()),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTeamMemberItem(Map<String, dynamic> userData) {
    final userSeq = userData['user_seq'].toString();
    final tempScore = userData['score'] ?? 0;
    final score = (scoreOpenRange == 'ALL') ? tempScore : '-';
    final nickname = userData['nickname'] ?? 'User'; // '유저'
    final profileImg = userData['profile_img'] ?? '';
    print('profileImg: $profileImg');

    final bool isActive = _userListMap[userSeq] ?? true;
    final hasExited = !isActive;

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

  Future<void> _onTapUser(Map<String, dynamic> userData) async {
    if (myParticipantType == 'ADMIN') { // 사회자 권한
      await showDialog(
        context: context,
        builder: (_) => ScoreEditDialog(
          roomSeq: widget.roomSeq,
          roomType: 'TEAM',
          userData: userData,
        ),
      );
    } else {
      await showDialog(
        context: context,
        builder: (_) => UserInfoBasicDialog(userData: userData),
      );
    }
  }
}
