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

// Server request (서버 API 요청)
import '../../plugins/api.dart';
// Response modal (응답 모달)
import 'response_dialog.dart';

class RoomSettingModal extends StatefulWidget {
  final Map<String, dynamic> roomInfo; 
  // 방 정보 예시:
  // {
  //   "room_seq": "13",
  //   "room_master_yn": "Y",
  //   "room_title": "...",
  //   "room_type": "private" or "team",
  //   ...
  // }

  const RoomSettingModal({Key? key, required this.roomInfo}) : super(key: key);

  @override
  State<RoomSettingModal> createState() => _RoomSettingModalState();
}

class _RoomSettingModalState extends State<RoomSettingModal> {
  // ─────────────────────────────────────────
  // Local state (로컬 상태)
  // ─────────────────────────────────────────
  late bool isMaster;             // whether user is the room master (방장 여부)
  String openYn = 'Y';            // open or private (공개/비공개)
  String roomPw = '';             // password if private (비공개 시 비번)
  late int roomSeq;               // room number (방 번호)
  String roomTitle = '';          // room title (방 제목)
  String roomIntro = '';          // room description (방 소개)
  int runningTime = 1;            // running time (운영 시간)
  int numberOfPeople = 10;        // max participants (최대 인원)
  String scoreOpenRange = 'PRIVATE'; // score visibility (점수 공개 범위) (PRIVATE / TEAM / ALL)

  // Firebase Realtime Database reference (FRD 관련)
  late DatabaseReference _roomRef;
  bool _isLoading = true;

  // Distinguish if room is "private" or "team" (개인전인지 팀전인지)
  late bool isPrivateType; 

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

    // (1) room_seq
    roomSeq = int.tryParse('${widget.roomInfo['room_seq'] ?? '0'}') ?? 0;

    // (2) room type
    final roomTypeStr = (widget.roomInfo['room_type'] ?? 'private').toString().toLowerCase();
    // if "private" => isPrivateType=true, else => isPrivateType=false
    isPrivateType = (roomTypeStr == 'private');

    // (3) firebase ref
    final roomKey = 'korea-$roomSeq';
    _roomRef = FirebaseDatabase.instance.ref('rooms/$roomKey/roomInfo');

    // (4) compare my_user_seq with master_user_seq + read roomInfo from FRD
    _checkMasterAndFetchData();
  }

  /// Load my_user_seq from local storage,
  /// then read roomInfo from FRD and update state
  /// (로컬스토리지에서 my_user_seq 불러오고 FRD에서 roomInfo 읽어서 state 업데이트)
  Future<void> _checkMasterAndFetchData() async {
    final prefs = await SharedPreferences.getInstance();
    final myUserSeq = prefs.getInt('my_user_seq') ?? 0;

    final snapshot = await _roomRef.get();
    if (!snapshot.exists) {
      // No room info (방 정보 없음)
      setState(() {
        _isLoading = false;
        isMaster = false;
        roomTitle = 'No room info'; 
        // '방 정보 없음'
      });
      return;
    }

    final data = snapshot.value as Map<dynamic, dynamic>? ?? {};
    // e.g. master_user_seq, open_yn, etc
    final masterSeq = data['master_user_seq'] ?? 0;

    setState(() {
      isMaster = (masterSeq.toString() == myUserSeq.toString());

      // fill fields (각 필드들)
      roomTitle       = data['room_title']?.toString()       ?? '';
      roomIntro       = data['room_intro']?.toString()       ?? '';
      openYn          = data['open_yn']?.toString()          ?? 'Y';
      roomPw          = data['room_pw']?.toString()          ?? '';
      runningTime     = _toInt(data['running_time'], 1);
      numberOfPeople  = _toInt(data['number_of_people'], 10);
      scoreOpenRange  = data['score_open_range']?.toString() ?? 'PRIVATE';

      _isLoading = false;
    });
  }

  /// simple int conversion (단순 int 변환 유틸)
  int _toInt(dynamic val, int defaultVal) {
    if (val == null) return defaultVal;
    if (val is int) return val;
    if (val is String) {
      return int.tryParse(val) ?? defaultVal;
    }
    return defaultVal;
  }

  /// "Update" button click (수정 버튼 클릭)
  Future<void> _onUpdate() async {
    // server request to update room settings (서버 API로 방 설정 수정)
    final requestBody = {
      'room_seq': '$roomSeq',
      'room_status': 'WAIT',
      'room_title': roomTitle,
      'room_intro': roomIntro,
      'open_yn': openYn,
      'room_pw': roomPw,
      'running_time': '$runningTime',
      'room_type': widget.roomInfo['room_type'] ?? 'private',
      'number_of_people': '$numberOfPeople',
      'score_open_range': scoreOpenRange,
    };

    // If team game, add number_of_teams (팀전이면 number_of_teams 추가)
    if (!isPrivateType) {
      // e.g. assume '4' or fetch from FRD
      requestBody['number_of_teams'] = '4';
    }

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/update/room/setting/info',
        body: requestBody,
      );

      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        final serverResult = resp['result'] ?? 'FAIL';
        if (serverResult == 'OK') {
          // success (성공)
          await showDialog(
            context: context,
            builder: (_) => AlertDialog(
              backgroundColor: Colors.white,
              content: const Text('Room settings have been updated successfully.'
                  // '방 설정이 성공적으로 수정되었습니다.'
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('OK'),
                ),
              ],
            ),
          );
          Navigator.pop(context, 'refresh');
        } else {
          // internal failure (내부 실패)
          final msgTitle = resp['response_info']?['msg_title'] ?? 'Update Failed'
              // '수정 실패'
              ;
          final msgContent = resp['response_info']?['msg_content'] ?? 'An error occurred.'
              // '오류가 발생했습니다.'
              ;
          showDialog(
            context: context,
            builder: (_) => AlertDialog(
              backgroundColor: Colors.white,
              content: Text('$msgTitle\n$msgContent'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('OK'),
                ),
              ],
            ),
          );
        }
      } else {
        // server communication failure (서버 통신 실패)
        showDialog(
          context: context,
          builder: (_) => AlertDialog(
            backgroundColor: Colors.white,
            content: const Text('Failed - Server communication error.'
                // '실패 - 서버 통신에 실패했습니다.'
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('OK'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      // request error (요청 중 오류)
      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          backgroundColor: Colors.white,
          content: Text('Error occurred while making request.\n$e'
              // '서버 요청 중 오류가 발생했습니다.\n$e'
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('OK'),
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: _isLoading
          ? const SizedBox(
              height: 100,
              child: Center(child: CircularProgressIndicator()),
            )
          : SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Modal top title (모달 상단 제목)
                  Text(
                    'Room Settings',
                    // '방 설정 정보'
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.black.withOpacity(0.9),
                    ),
                  ),
                  const SizedBox(height: 12),

                  // (1) Room title (방 제목)
                  _buildTitle('Room Title' 
                      // '방 제목'
                  ),
                  TextField(
                    readOnly: !isMaster,
                    controller: TextEditingController(text: roomTitle),
                    onChanged: (value) => roomTitle = value,
                    style: const TextStyle(color: Colors.black),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black.withOpacity(0.8)),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      isDense: true,
                    ),
                  ),
                  const SizedBox(height: 12),

                  // (2) Room introduction (방 소개)
                  _buildTitle('Room Description' 
                      // '방 소개'
                  ),
                  SizedBox(
                    height: 60,
                    child: TextField(
                      readOnly: !isMaster,
                      controller: TextEditingController(text: roomIntro),
                      onChanged: (value) => roomIntro = value,
                      maxLines: null,
                      expands: true,
                      style: const TextStyle(color: Colors.black),
                      textAlignVertical: TextAlignVertical.top,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderSide: BorderSide(color: Colors.black.withOpacity(0.8)),
                        ),
                        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        isDense: true,
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),

                  // (3) Password setting (공개/비공개)
                  _buildTitle('Password Setting' 
                      // '비밀번호 설정'
                  ),
                  Row(
                    children: [
                      Radio<String>(
                        value: 'Y',
                        groupValue: openYn,
                        activeColor: Colors.black,
                        onChanged: isMaster
                            ? (val) {
                                setState(() {
                                  openYn = val ?? 'Y';
                                });
                              }
                            : null,
                      ),
                      const Text('Open'
                          // '공개'
                          , style: TextStyle(color: Colors.black)),
                      const SizedBox(width: 8),
                      Radio<String>(
                        value: 'N',
                        groupValue: openYn,
                        activeColor: Colors.black,
                        onChanged: isMaster
                            ? (val) {
                                setState(() {
                                  openYn = val ?? 'N';
                                });
                              }
                            : null,
                      ),
                      const Text('Private'
                          // '비공개'
                          , style: TextStyle(color: Colors.black)),
                    ],
                  ),
                  if (openYn == 'N') ...[
                    SizedBox(
                      height: 40,
                      child: TextField(
                        readOnly: !isMaster,
                        obscureText: true,
                        onChanged: (value) => roomPw = value,
                        style: const TextStyle(color: Colors.black),
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.black.withOpacity(0.8)),
                          ),
                          hintText: 'Enter password'
                              // '비밀번호 입력'
                          ,
                          hintStyle: TextStyle(color: Colors.black.withOpacity(0.4)),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          isDense: true,
                        ),
                      ),
                    ),
                    const SizedBox(height: 12),
                  ],

                  // (4) Running time (운영시간)
                  _buildTitle('Running Time' 
                      // '운영시간'
                  ),
                  Row(
                    children: [
                      DropdownButton<int>(
                        value: runningTime,
                        dropdownColor: Colors.white,
                        style: const TextStyle(color: Colors.black),
                        underline: Container(
                          height: 1,
                          color: Colors.black.withOpacity(0.8),
                        ),
                        items: [1, 2, 3, 4, 5, 6]
                            .map((e) => DropdownMenuItem<int>(
                                  value: e,
                                  child: Text('$e', style: const TextStyle(color: Colors.black)),
                                ))
                            .toList(),
                        onChanged: isMaster
                            ? (val) {
                                if (val == null) return;
                                setState(() {
                                  runningTime = val;
                                });
                              }
                            : null,
                      ),
                      const SizedBox(width: 8),
                      const Text('hr' 
                          // '시간'
                          , style: TextStyle(color: Colors.black)),
                    ],
                  ),
                  const SizedBox(height: 12),

                  // (5) Max participants (최대 인원수)
                  _buildTitle('Max Participants' 
                      // '최대 인원수'
                  ),
                  Row(
                    children: [
                      SizedBox(
                        width: 80,
                        height: 40,
                        child: TextField(
                          readOnly: !isMaster,
                          controller: TextEditingController(text: '$numberOfPeople'),
                          keyboardType: TextInputType.number,
                          onChanged: (value) {
                            setState(() {
                              numberOfPeople = int.tryParse(value) ?? numberOfPeople;
                            });
                          },
                          style: const TextStyle(color: Colors.black),
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.black.withOpacity(0.8)),
                            ),
                            contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                            isDense: true,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      const Text('people', 
                          // '명'
                          style: TextStyle(color: Colors.black)),
                    ],
                  ),
                  const SizedBox(height: 12),

                  // (6) Score visibility (점수 공개 범위)
                  _buildTitle('Score Visibility'
                      // '점수 공개 범위'
                  ),
                  // If private game => PRIVATE or ALL
                  // If team game => PRIVATE, TEAM, ALL
                  if (isPrivateType)
                    Column(
                      children: [
                        RadioListTile<String>(
                          value: 'PRIVATE',
                          groupValue: scoreOpenRange,
                          activeColor: Colors.black,
                          title: const Text(
                            'Private'
                            // '개인'
                            ,
                            style: TextStyle(color: Colors.black),
                          ),
                          onChanged: isMaster
                              ? (val) {
                                  if (val != null) {
                                    setState(() => scoreOpenRange = val);
                                  }
                                }
                              : null,
                        ),
                        RadioListTile<String>(
                          value: 'ALL',
                          groupValue: scoreOpenRange,
                          activeColor: Colors.black,
                          title: const Text(
                            'Public'
                            // '전체'
                            ,
                            style: TextStyle(color: Colors.black),
                          ),
                          onChanged: isMaster
                              ? (val) {
                                  if (val != null) {
                                    setState(() => scoreOpenRange = val);
                                  }
                                }
                              : null,
                        ),
                      ],
                    )
                  else
                    Column(
                      children: [
                        RadioListTile<String>(
                          value: 'PRIVATE',
                          groupValue: scoreOpenRange,
                          activeColor: Colors.black,
                          title: const Text(
                            'Private'
                            // '개인'
                            ,
                            style: TextStyle(color: Colors.black),
                          ),
                          onChanged: isMaster
                              ? (val) {
                                  if (val != null) {
                                    setState(() => scoreOpenRange = val);
                                  }
                                }
                              : null,
                        ),
                        RadioListTile<String>(
                          value: 'TEAM',
                          groupValue: scoreOpenRange,
                          activeColor: Colors.black,
                          title: const Text(
                            'Team'
                            // '팀'
                            ,
                            style: TextStyle(color: Colors.black),
                          ),
                          onChanged: isMaster
                              ? (val) {
                                  if (val != null) {
                                    setState(() => scoreOpenRange = val);
                                  }
                                }
                              : null,
                        ),
                        RadioListTile<String>(
                          value: 'ALL',
                          groupValue: scoreOpenRange,
                          activeColor: Colors.black,
                          title: const Text(
                            'Public'
                            // '전체'
                            ,
                            style: TextStyle(color: Colors.black),
                          ),
                          onChanged: isMaster
                              ? (val) {
                                  if (val != null) {
                                    setState(() => scoreOpenRange = val);
                                  }
                                }
                              : null,
                        ),
                      ],
                    ),
                  const SizedBox(height: 20),

                  // (7) Bottom buttons (하단 버튼)
                  if (isMaster)
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        ElevatedButton(
                          onPressed: _onUpdate,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.black,
                            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                          ),
                          child: const Text(
                            'Update', 
                            // '수정'
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                        ElevatedButton(
                          onPressed: () => Navigator.pop(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.black,
                            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                          ),
                          child: const Text(
                            'OK'
                            // '확인'
                            , style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    )
                  else
                    Center(
                      child: ElevatedButton(
                        onPressed: () => Navigator.pop(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 12),
                        ),
                        child: const Text(
                          'OK'
                          // '확인'
                          , style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                ],
              ),
            ),
    );
  }

  /// A black-and-white style label (블랙 앤 화이트 컨셉의 타이틀(레이블) 텍스트)
  Widget _buildTitle(String label) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        label,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 14,
          color: Colors.black.withOpacity(0.9),
        ),
      ),
    );
  }
}
