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 UserInfoPrivateDialog extends StatefulWidget {
  final Map<String, dynamic> userData; 
  /* 유저 데이터 */
  final bool isRoomMaster;  
  /* 현재 로그인 유저가 방장인지 */
  final int roomSeq;        
  /* 방 번호 */
  final String roomTypeName; 
  /* "PRIVATE" */

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

  @override
  State<UserInfoPrivateDialog> createState() => _UserInfoPrivateDialogState();
}

class _UserInfoPrivateDialogState extends State<UserInfoPrivateDialog> {
  late String participantType; 
  /* 'ADMIN' or 'PLAYER' */
  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';
    introduceMyself = widget.userData['introduce_myself'] ?? '';
  }

  @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);
    });
  }

  /// API to update role (for Room Master only) 
  /// /* 역할 변경 API (방장 전용) */
  Future<void> _onUpdateUserInfo() async {
    if (!widget.isRoomMaster) return; 
    // /* 방장만 수정하기 가능 */

    final requestBody = {
      'room_seq': '${widget.roomSeq}',
      'room_type_name': widget.roomTypeName, 
      'target_user_seq': '${widget.userData['user_seq']}',
      'participant_type': participantType,
    };

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/update/user/role',
        body: requestBody,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          await showResponseDialog(
            context, 
            'Success' /* '성공' */, 
            'Role has been successfully updated.' 
            /* '역할이 성공적으로 수정되었습니다.' */
          );
          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');
    }
  }

  /// Kick participant (Room Master only) 
  /// /* 새로 추가: "추방하기" (방장 전용) */
  Future<void> _onKickParticipant() async {
    if (!widget.isRoomMaster) return; 
    /* 방장이 아닌데 추방 시도 -> 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' /* '오류' */, 
        'The master cannot be kicked out.' 
        /* '방장은 추방할 수 없습니다.' */
      );
      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' 
            /* '성공' */, 
            'The 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 department = widget.userData['department'] ?? 'No Department Info' 
        /* '소속정보없음' */;
    final profileImg = widget.userData['profile_img'] ?? '';
    // 서버 주소
    final baseUrl = Config.baseUrl;

    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      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: [
                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'
                                /* '이미지\n불가' */,
                                textAlign: TextAlign.center,
                              ),
                            ),
                          )
                        : const Center(
                            child: Text(
                              'No\nImage'
                              /* '이미지\n없음' */,
                              textAlign: TextAlign.center,
                            ),
                          ),
                  ),
                ),
                const SizedBox(width: 16),
                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) Room master can update role 
            // /* 방장이면 역할 수정 가능 */
            if (widget.isRoomMaster) ...[
              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),
            ] else ...[
              Text(
                'Role: $participantType'
                /* '역할: $participantType' */,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
            ],

            // (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: [
                  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: FittedBox(
                        fit: BoxFit.contain,
                        child: Text(
                          'Update'
                          /* '수정' */,
                          style: TextStyle(color: Colors.white, fontSize: 12 * scaleFactor),
                        ),
                      ),
                    ),
                  ),
                  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: FittedBox(
                        fit: BoxFit.contain,
                        child: Text(
                          'Kick'
                          /* '추방' */,
                          style: TextStyle(color: Colors.white, fontSize: 12 * scaleFactor),
                        ),
                      ),
                    ),
                  ),
                  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: FittedBox(
                        fit: BoxFit.contain,
                        child: Text(
                          'OK'
                          /* '확인' */,
                          style: TextStyle(color: Colors.white, fontSize: 12 * scaleFactor),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ] 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: FittedBox(
                    fit: BoxFit.contain,
                    child: Text(
                      'OK'
                      /* '확인' */,
                      style: TextStyle(color: Colors.white, fontSize: 12 * scaleFactor),
                    ),
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
