import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart'; // SharedPreferences 임포트
import '../plugins/api.dart';             // server request (서버 요청)
import 'response_dialog.dart';           // response modal (오류/알림 모달)

// For waiting rooms
import '../../views/room/waiting_room_team_page.dart';    // 팀전 대기방
import '../../views/room/waiting_room_private_page.dart'; // 개인전 대기방

/// A separate room detail modal (분리된 방 상세 모달)
class RoomDetailDialog extends StatefulWidget {
  final Map<String, dynamic> roomData; 
  // 방 정보

  const RoomDetailDialog({Key? key, required this.roomData}) : super(key: key);

  @override
  State<RoomDetailDialog> createState() => _RoomDetailDialogState();
}

class _RoomDetailDialogState extends State<RoomDetailDialog> {
  late String roomTitle;
  /* 방 제목 */
  late String roomIntro;
  /* 방 소개 */
  late String roomStatus; 
  /* '대기중'/'진행중'/'종료' */
  late String openYn;     
  /* '공개'/'비공개' */
  late bool isPrivate;    
  /* 비공개 여부 (openYn=='비공개' => true) */
  late bool isWait;       
  /* 대기중 여부 */
  late bool isRunning;    
  /* 진행중 여부 */
  late bool isFinish;     
  /* 종료 여부 */

  late int roomSeq;       
  /* 서버에 전달할 방 번호 */
  late String roomType;   
  /* 서버에 전달할 방 타입 ("private"/"team") */

  final TextEditingController _pwController = TextEditingController();
  // 비밀번호 입력 컨트롤러 (비공개 + 대기중 일 때만 표시)

  @override
  void initState() {
    super.initState();
    // Extract fields from roomData (roomData에서 필요한 필드 추출)
    roomTitle  = widget.roomData['room_title']  ?? '(No Title)'; 
    // '(방제목 없음)'
    roomIntro  = widget.roomData['room_intro']  ?? '';
    roomStatus = widget.roomData['room_status'] ?? 'Waiting'; 
    // '대기중'
    openYn     = widget.roomData['open_yn']     ?? 'Open'; 
    // '공개'

    // Info to send to server (서버에 전송할 정보)
    roomSeq  = widget.roomData['room_seq']  ?? 0;
    roomType = widget.roomData['room_type'] ?? 'private'; 
    // e.g. "team" vs "private"

    // If openYn == '비공개', treat as private (isPrivate = true)
    // '비공개' => true, else => false
    isPrivate = (openYn == '비공개');

    // State flags (상태별 flag)
    // originally '대기중' => isWait, '진행중' => isRunning, '종료' => isFinish
    isWait    = (roomStatus == '대기중' || roomStatus.toLowerCase() == 'waiting');
    isRunning = (roomStatus == '진행중' || roomStatus.toLowerCase() == 'running');
    isFinish  = (roomStatus == '종료'   || roomStatus.toLowerCase() == 'finish');
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        // White background + some padding (흰 배경 + 여유 간격)
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // (A) Title at top, centered (상단 방제목, 가운데 정렬)
            Center(
              child: Text(
                roomTitle,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
            ),
            const SizedBox(height: 20),

            // (B) "Room Intro" label (방 소개 라벨)
            const Text(
              'Room Description',
              // '방 소개'
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.black,
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 6),

            // (C) roomIntro area (방 소개 영역)
            Container(
              height: 80,
              padding: const EdgeInsets.all(8),
              child: SingleChildScrollView(
                child: Text(
                  roomIntro.isNotEmpty 
                      ? roomIntro 
                      : 'No description provided.',
                  // '소개글이 없습니다.'
                  style: const TextStyle(color: Colors.black),
                ),
              ),
            ),
            const SizedBox(height: 16),

            // (D) open or private (공개/비공개)
            Text(
              isPrivate ? 'Private Room'
                // '비공개방'
                : 'Open Room'
                // '공개방'
              ,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
            // (D-1) password field if private + waiting (비공개 + 대기중)
            if (isPrivate && isWait) ...[
              const SizedBox(height: 16),
              TextField(
                controller: _pwController,
                obscureText: true,
                decoration: const InputDecoration(
                  labelText: 'Password'
                  // '비밀번호'
                  ,
                  labelStyle: TextStyle(color: Colors.black),
                  border: OutlineInputBorder(),
                ),
              ),
            ],
            const SizedBox(height: 24),

            // (E) bottom button row (하단 버튼)
            _buildBottomButton(),
          ],
        ),
      ),
    );
  }

  /// Bottom button area (하단 버튼 구역)
  Widget _buildBottomButton() {
    if (isWait) {
      // (A) If waiting => "Enter" + "Close" (대기중 -> "입장" + "닫기")
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildBlackButton(
            label: 'Enter'
            // '입장'
            ,
            onTap: _onEnterRoom,
          ),
          _buildBlackButton(
            label: 'Close'
            // '닫기'
            ,
            onTap: () => Navigator.pop(context),
          ),
        ],
      );
    } else if (isRunning) {
      // (B) If running => only "OK" in center (진행중 -> "확인")
      return Center(
        child: _buildBlackButton(
          label: 'OK'
          // '확인'
          ,
          onTap: () => Navigator.pop(context),
        ),
      );
    } else {
      // (C) If finished => "View Results" + "OK" (종료 -> "결과보기", "확인")
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SizedBox(
            width: 100,
            child: _buildBlackButton(
              label: 'View Results'
              // '결과보기'
              ,
              onTap: () {
                // TODO: result logic
                Navigator.pop(context);
              },
            ),
          ),
          SizedBox(
            width: 100,
            child: _buildBlackButton(
              label: 'OK'
              // '확인'
              ,
              onTap: () => Navigator.pop(context),
            ),
          ),
        ],
      );
    }
  }

  /// "Enter" room logic ("입장" 버튼 로직)
  Future<void> _onEnterRoom() async {
    final pw = _pwController.text.trim();

    final requestBody = {
      "room_seq": "$roomSeq",
      "room_type": roomType, 
      "room_pw": pw, 
    };

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

      if (response == null || response['result'] != 'OK') {
        // Communication error (서버 통신 오류)
        showResponseDialog(context, 'Error', 'Failed to enter the room. Server communication error.'
          // '방 입장 실패. 서버 통신 오류.'
        );
        return;
      }

      final resp = response['response'] ?? {};
      if (resp['result'] == 'OK') {
        // success (성공)
        Navigator.pop(context); // Close this modal (모달 닫기)

        // If it's a team room => push to waiting_room_team_page
        // else => waiting_room_private_page
        if (roomType.toLowerCase() == 'team') {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (_) => WaitingRoomTeamPage(
                roomSeq: roomSeq,
                roomType: 'team',
              ),
            ),
          );
        } else {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (_) => WaitingRoomPrivatePage(
                roomSeq: roomSeq,
                roomType: 'private',
              ),
            ),
          );
        }
      } else {
        // internal fail (내부 실패)
        final msgTitle = resp['response_info']?['msg_title'] ?? 'Failed to enter room'
            // '방 입장 실패'
            ;
        final msgContent = resp['response_info']?['msg_content'] ?? 'An error occurred.'
            // '오류가 발생했습니다.'
            ;
        showResponseDialog(context, msgTitle, msgContent);
      }
    } catch (e) {
      showResponseDialog(context, 'Error', 'An exception occurred during server request: $e'
        // '서버 요청 중 예외 발생: $e'
      );
    }
  }

  /// Common styled black button (공통 버튼)
  Widget _buildBlackButton({
    required String label,
    required VoidCallback onTap,
  }) {
    return ElevatedButton(
      onPressed: onTap,
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
      child: Text(label, style: const TextStyle(fontSize: 14)),
    );
  }
}
