import 'package:flutter/material.dart';
import 'response_dialog.dart';
import '../../plugins/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:auto_size_text/auto_size_text.dart';
import '../config/config.dart';

class UserInfoTeamDialog extends StatefulWidget {
  final Map<String, dynamic> userData;  
  /* 유저 데이터 */
  final bool isRoomMaster;       
  /* 이 모달을 연 "현재 로그인 유저"가 방장인지 여부 */
  final int roomSeq;            
  /* 방 번호 */
  final String roomTypeName;    
  /* "TEAM" */
  final List<String> teamNameList; 
  /* 팀명 목록 */

  const UserInfoTeamDialog({
    Key? key,
    required this.userData,
    required this.isRoomMaster,
    required this.roomSeq,
    required this.roomTypeName,
    required this.teamNameList,
  }) : super(key: key);

  @override
  State<UserInfoTeamDialog> createState() => _UserInfoTeamDialogState();
}

class _UserInfoTeamDialogState extends State<UserInfoTeamDialog> {
  late String participantType; 
  /* 'ADMIN' / 'PLAYER' */
  late String teamName;        
  /* 'A'/'B'/'WAIT' */
  late String introduceMyself; 
  /* 유저 소개 */

  double scaleFactor = 1.0;
  /* 화면 크기에 따라 폰트 크기 조절 */
  double buttonScaleFactor = 1.0;

  @override
  void initState() {
    super.initState();
    final rawType = (widget.userData['participant_type'] ?? 'PLAYER').toString().toUpperCase();
    participantType = (rawType == 'ADMIN') ? 'ADMIN' : 'PLAYER';

    final rawTeam = (widget.userData['team_name'] ?? '').toString().trim().toUpperCase();
    teamName = (rawTeam.isEmpty || rawTeam == 'WAIT') ? 'WAIT' : rawTeam;

    introduceMyself = widget.userData['introduce_myself'] ?? '';

    // If WAIT is not in the teamNameList, add it
    // /* teamNameList에 WAIT 없으면 추가 */
    final hasWait = widget.teamNameList.map((e) => e.toUpperCase()).contains('WAIT');
    if (!hasWait) {
      widget.teamNameList.add('WAIT');
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _updateScaleFactor();
  }

  // Adjust font size by screen width (화면 크기에 따라 폰트 크기 조절)
  void _updateScaleFactor() {
    final screenWidth = MediaQuery.of(context).size.width;
    const baseWidth = 450.0;
    setState(() {
      scaleFactor = (screenWidth / baseWidth).clamp(0.8, 1.2);
      buttonScaleFactor = (screenWidth / baseWidth).clamp(0.6, 1.2);
    });
  }

  /// (1) API to update role/team (역할/팀 수정 API)
  Future<void> _onUpdateUserInfo() async {
    if (!widget.isRoomMaster) return; 
    // /* 방장이 아닌데 수정 시도 -> return */

    final reqBody = {
      'room_seq': '${widget.roomSeq}',
      'room_type_name': widget.roomTypeName, // "TEAM"
      'target_user_seq': '${widget.userData['user_seq']}',
      'participant_type': participantType,   
      'team_name': teamName,
    };

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/update/user/role',
        body: reqBody,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          await showResponseDialog(
            context, 
            'Success' 
            /* '성공' */, 
            'Role/team updated successfully.'
            /* '역할/팀이 성공적으로 수정되었습니다.' */
          );
          Navigator.pop(context, 'refresh');
        } else {
          final msgTitle = resp['response_info']?['msg_title'] ?? 'Error'
              /* '오류' */;
          final msgContent = resp['response_info']?['msg_content'] ?? 'Update failed'
              /* '수정 실패' */;
          showResponseDialog(context, msgTitle, msgContent);
        }
      } else {
        showResponseDialog(context, 'Failed' 
          /* '실패' */, 'Server communication failed.'
          /* '서버 통신 실패' */);
      }
    } catch (e) {
      showResponseDialog(context, 'Error occurred' 
        /* '오류 발생' */, '$e');
    }
  }

  /// (2) New: Kick participant API call (추방하기 API)
  Future<void> _onKickParticipant() async {
    if (!widget.isRoomMaster) return; 
    // /* 방장이 아니면 리턴 */

    final prefs = await SharedPreferences.getInstance();
    final mySeq = prefs.getInt('my_user_seq')?.toString() ?? '0';
    if (widget.userData['user_seq'] == mySeq) {
      await showResponseDialog(
        context, 
        'Error' 
        /* '오류' */, 
        'You cannot kick yourself (the master).'
        /* '방장은 추방할 수 없습니다.' */
      );
      return;
    }

    final reqBody = {
      "room_seq": "${widget.roomSeq}",
      "target_user_seq": "${widget.userData['user_seq']}",
    };

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/kick/participant',
        body: reqBody,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          await showResponseDialog(
            context, 
            'Success'
            /* '성공' */, 
            'User has been kicked out.'
            /* '해당 유저가 강퇴되었습니다.' */
          );
          Navigator.pop(context, 'refresh');
        } else {
          final msgTitle = resp['response_info']?['msg_title'] ?? 'Error'
              /* '오류' */;
          final msgContent = resp['response_info']?['msg_content'] ?? 'Kick-out failed'
              /* '강퇴 실패' */;
          showResponseDialog(context, msgTitle, msgContent);
        }
      } else {
        showResponseDialog(context, 'Failed'
          /* '실패' */, 'Server communication failed.'
          /* '서버 통신 실패' */);
      }
    } catch (e) {
      showResponseDialog(context, 'Error occurred'
        /* '오류 발생' */, '$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final userName   = widget.userData['nickname'] ?? 'User'
        /* '유저' */;
    final profileImg = widget.userData['profile_img'] ?? '';
    final department = widget.userData['department'] ?? 'No Department Info'
        /* '소속정보 없음' */;

    // 서버 주소
    final baseUrl = Config.baseUrl;

    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      insetPadding: const EdgeInsets.symmetric(horizontal: 20),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              'User Info' 
              /* '유저 정보' */,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),

            // (A) Profile section (프로필 영역)
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Profile image (프로필 이미지)
                Container(
                  width: 80, 
                  height: 80,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(16),
                    child: (profileImg.isNotEmpty)
                        ? Image.network(
                            '$baseUrl/images$profileImg',
                            fit: BoxFit.cover,
                            errorBuilder: (ctx, err, st) => const Center(
                              child: Text(
                                'Image\nError', 
                                textAlign: TextAlign.center,
                              ),
                            ),
                          )
                        : const Center(
                            child: Text(
                              'No\nImage',
                              textAlign: TextAlign.center,
                            ),
                          ),
                  ),
                ),
                const SizedBox(width: 16),
                // Nickname + Department (닉네임 + 소속)
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        userName, 
                        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      const SizedBox(height: 6),
                      Text(
                        department, 
                        style: const TextStyle(fontSize: 14),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // (B) Only room master can update role/team (방장만 역할/팀 수정)
            if (widget.isRoomMaster) ...[
              // Role dropdown (역할 드롭다운)
              Row(
                children: [
                  const Text(
                    'Role: ', 
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  DropdownButton<String>(
                    value: participantType,
                    items: const [
                      DropdownMenuItem(
                        value: 'ADMIN', 
                        child: Text('Moderator'),
                      ),
                      DropdownMenuItem(
                        value: 'PLAYER', 
                        child: Text('Participant'),
                      ),
                    ],
                    onChanged: (val) {
                      if (val == null) return;
                      setState(() {
                        participantType = val;
                      });
                    },
                  ),
                ],
              ),
              const SizedBox(height: 12),

              // Team name dropdown (팀명 드롭다운)
              Row(
                children: [
                  const Text(
                    'Team: ',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  DropdownButton<String>(
                    value: widget.teamNameList
                      .map((e) => e.toUpperCase())
                      .contains(teamName)
                      ? teamName
                      : 'WAIT',
                    items: widget.teamNameList.map((t) => DropdownMenuItem(
                      value: t.toUpperCase(),
                      child: Text(t),
                    )).toList(),
                    onChanged: (val) {
                      if (val == null) return;
                      setState(() {
                        teamName = val;
                      });
                    },
                  ),
                ],
              ),
              const SizedBox(height: 16),
            ] else ...[
              // (B') If not room master, just display info (일반유저 -> 정보만 표시)
              Text(
                'Role: $participantType' 
                /* '역할: $participantType' */,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 6),
              Text(
                'Team: $teamName'
                /* '팀명: $teamName' */,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),
            ],

            // (C) Introduction (소개)
            const Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Introduction' 
                /* '소개' */,
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 4),
            Container(
              width: double.infinity,
              height: 100,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
                borderRadius: BorderRadius.circular(8),
              ),
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(8),
                child: Text(
                  introduceMyself.isNotEmpty 
                      ? introduceMyself 
                      : 'No introduction.'
                        /* '소개글이 없습니다.' */,
                  style: const TextStyle(fontSize: 14),
                  softWrap: true,
                  maxLines: 100,
                  overflow: TextOverflow.clip,
                ),
              ),
            ),
            const SizedBox(height: 16),

            // (D) Bottom buttons (하단 버튼)
            if (widget.isRoomMaster) ...[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // "Update" (수정하기)
                  SizedBox(
                    width: 80 * scaleFactor,
                    height: 40 * scaleFactor,
                    child: ElevatedButton(
                      onPressed: _onUpdateUserInfo,
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                      child: AutoSizeText(
                        'Update'
                        /* '수정' */,
                        maxLines: 1,
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  // "Kick" (추방하기)
                  SizedBox(
                    width: 80 * scaleFactor,
                    height: 40 * scaleFactor,
                    child: ElevatedButton(
                      onPressed: _onKickParticipant,
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                      child: AutoSizeText(
                        'Kick'
                        /* '추방' */,
                        maxLines: 1,
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  // "OK" (확인)
                  SizedBox(
                    width: 80 * scaleFactor,
                    height: 40 * scaleFactor,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                      child: AutoSizeText(
                        'OK'
                        /* '확인' */,
                        maxLines: 1,
                        style: const TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ],
              ),
            ] else ...[
              SizedBox(
                width: 80 * scaleFactor,
                height: 40 * scaleFactor,
                child: ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                  child: AutoSizeText(
                    'OK'
                    /* '확인' */,
                    maxLines: 1,
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
