import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // restrict number input (숫자 입력 제한)
import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'waiting_room_team_page.dart';
import 'waiting_room_private_page.dart';

class CreateRoomPage extends StatefulWidget {
  const CreateRoomPage({Key? key}) : super(key: key);

  @override
  _CreateRoomPageState createState() => _CreateRoomPageState();
}

class _CreateRoomPageState extends State<CreateRoomPage> {
  final TextEditingController _roomNameController = TextEditingController();
  final TextEditingController _roomDescriptionController = TextEditingController();

  /// Public or private (open_yn: 'Y' / 'N')
  bool _isPrivate = false; // 공개 여부 (open_yn: 'Y'/'N')
  final TextEditingController _passwordController = TextEditingController();

  /// Running time (1~6 hours) (운영시간)
  int _selectedHour = 1;

  /// Game type: solo/team (게임 유형: 개인전/팀전)
  bool _isTeamGame = false;
  /// Team count (팀 수) if team game, minimum 2 teams
  int _selectedTeamCount = 2;

  /// Max participants (최대 인원)
  final TextEditingController _maxParticipantsController = TextEditingController(text: '1');

  /// Score open range (점수 공개 범위)
  /// - Solo: 'ALL' or 'PRIVATE'
  /// - Team: 'ALL', 'TEAM', or 'PRIVATE'
  String _selectedScoreOpenRange = 'ALL';

  @override
  void dispose() {
    _roomNameController.dispose();
    _roomDescriptionController.dispose();
    _passwordController.dispose();
    _maxParticipantsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // White background (전체 흰 배경)
      backgroundColor: Colors.white,

      appBar: AppBar(
        title: const Text(
          'Create Room', // '방 만들기'
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),

      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// (A) Room Title (방 제목)
            const Text(
              'Room Title', // '방 제목'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 6),
            _buildWhiteBorderTextField(
              controller: _roomNameController,
              hintText: 'Enter room title', // '방 제목을 입력하세요'
            ),
            const SizedBox(height: 16),

            /// (B) Room Description (방 소개)
            const Text(
              'Room Description', // '방 소개'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 6),
            _buildMultilineBox(
              controller: _roomDescriptionController,
              hintText: 'Enter room description', // '방 소개를 입력하세요'
            ),
            const SizedBox(height: 16),

            /// (C) Password setting (public / private) (비밀번호 설정)
            const Text(
              'Password Setup', // '비밀번호 설정'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Row(
              children: [
                Checkbox(
                  value: !_isPrivate,
                  activeColor: Colors.black,
                  checkColor: Colors.white,
                  onChanged: (value) {
                    setState(() {
                      // public == !private (공개 == !비공개)
                      _isPrivate = !value!;
                    });
                  },
                ),
                const Text('Public'), // '공개'
                const SizedBox(width: 10),
                Checkbox(
                  value: _isPrivate,
                  activeColor: Colors.black,
                  checkColor: Colors.white,
                  onChanged: (value) {
                    setState(() {
                      _isPrivate = value!;
                    });
                  },
                ),
                const Text('Private'), // '비공개'
              ],
            ),
            if (_isPrivate)
              _buildWhiteBorderTextField(
                controller: _passwordController,
                hintText: 'Enter password', // '비밀번호를 입력하세요'
                obscureText: true,
              ),
            const SizedBox(height: 16),

            /// (D) Running time (1~6 hours) (운영시간 설정)
            const Text(
              'Running Time', // '운영시간 설정'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Row(
              children: [
                DropdownButton<int>(
                  value: _selectedHour,
                  dropdownColor: Colors.white,
                  style: const TextStyle(color: Colors.black),
                  items: List.generate(6, (index) => index + 1)
                      .map((value) => DropdownMenuItem<int>(
                            value: value,
                            child: Text(value.toString()),
                          ))
                      .toList(),
                  onChanged: (value) {
                    setState(() {
                      _selectedHour = value!;
                    });
                  },
                ),
                const SizedBox(width: 8),
                const Text('Hour'), // '시간'
              ],
            ),
            const SizedBox(height: 16),

            /// (E) Game type: solo/team (게임 유형: 개인전/팀전)
            const Text(
              'Game Type', // '게임 유형'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Row(
              children: [
                Checkbox(
                  value: !_isTeamGame,
                  activeColor: Colors.black,
                  checkColor: Colors.white,
                  onChanged: (value) {
                    setState(() {
                      _isTeamGame = !value!;
                      // Reset score open range (점수 공개 범위 초기화)
                      _selectedScoreOpenRange = 'ALL';
                    });
                  },
                ),
                const Text('Solo'), // '개인전'
                const SizedBox(width: 10),
                Checkbox(
                  value: _isTeamGame,
                  activeColor: Colors.black,
                  checkColor: Colors.white,
                  onChanged: (value) {
                    setState(() {
                      _isTeamGame = value!;
                      // Reset score open range (점수 공개 범위 초기화)
                      _selectedScoreOpenRange = 'ALL';
                    });
                  },
                ),
                const Text('Team'), // '팀전'
                const SizedBox(width: 16),
                if (_isTeamGame) ...[
                  const Text('Teams: '), // '팀수: '
                  const SizedBox(width: 8),
                  // Minimum 2 teams (팀은 최소 2팀)
                  DropdownButton<int>(
                    value: _selectedTeamCount,
                    dropdownColor: Colors.white,
                    style: const TextStyle(color: Colors.black),
                    items: List.generate(9, (index) => index + 2) // 2 ~ 10
                        .map((value) => DropdownMenuItem<int>(
                              value: value,
                              child: Text(value.toString()),
                            ))
                        .toList(),
                    onChanged: (value) {
                      setState(() {
                        _selectedTeamCount = value!;
                      });
                    },
                  ),
                ],
              ],
            ),
            const SizedBox(height: 16),

            /// (F) Max participants (최대 인원수)
            const Text(
              'Max Participants', // '최대 인원수'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Row(
              children: [
                SizedBox(
                  width: 80,
                  child: TextField(
                    controller: _maxParticipantsController,
                    keyboardType: TextInputType.number,
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 16),
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(vertical: 8),
                    ),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(3),
                    ],
                    onChanged: (value) {
                      if (value.isNotEmpty) {
                        final number = int.tryParse(value);
                        if (number == null || number < 1 || number > 100) {
                          _maxParticipantsController.text = '1';
                          _maxParticipantsController.selection =
                              TextSelection.fromPosition(
                            TextPosition(
                              offset: _maxParticipantsController.text.length,
                            ),
                          );
                        }
                      }
                    },
                  ),
                ),
                const SizedBox(width: 8),
                const Text('people', style: TextStyle(fontSize: 16)), // '명'
              ],
            ),
            const SizedBox(height: 16),

            /// (G) Score open range (점수 공개 범위)
            ///   Solo: 'ALL', 'PRIVATE'
            ///   Team: 'ALL', 'TEAM', 'PRIVATE'
            const Text(
              'Score Visibility', // '점수 공개 범위 설정'
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),

            if (!_isTeamGame)
              // Solo → ALL, PRIVATE (개인전)
              Column(
                children: [
                  RadioListTile<String>(
                    title: const Text('All'), // '전체'
                    value: 'ALL',
                    groupValue: _selectedScoreOpenRange,
                    activeColor: Colors.black,
                    onChanged: (value) {
                      setState(() {
                        _selectedScoreOpenRange = value!;
                      });
                    },
                  ),
                  RadioListTile<String>(
                    title: const Text('Private'), // '개인'
                    value: 'PRIVATE',
                    groupValue: _selectedScoreOpenRange,
                    activeColor: Colors.black,
                    onChanged: (value) {
                      setState(() {
                        _selectedScoreOpenRange = value!;
                      });
                    },
                  ),
                ],
              )
            else
              // Team → ALL, TEAM, PRIVATE (팀전)
              Column(
                children: [
                  RadioListTile<String>(
                    title: const Text('All'), // '전체'
                    value: 'ALL',
                    groupValue: _selectedScoreOpenRange,
                    activeColor: Colors.black,
                    onChanged: (value) {
                      setState(() {
                        _selectedScoreOpenRange = value!;
                      });
                    },
                  ),
                  RadioListTile<String>(
                    title: const Text('Team'), // '팀'
                    value: 'TEAM',
                    groupValue: _selectedScoreOpenRange,
                    activeColor: Colors.black,
                    onChanged: (value) {
                      setState(() {
                        _selectedScoreOpenRange = value!;
                      });
                    },
                  ),
                  RadioListTile<String>(
                    title: const Text('Private'), // '개인'
                    value: 'PRIVATE',
                    groupValue: _selectedScoreOpenRange,
                    activeColor: Colors.black,
                    onChanged: (value) {
                      setState(() {
                        _selectedScoreOpenRange = value!;
                      });
                    },
                  ),
                ],
              ),
            const SizedBox(height: 24),

            /// (H) "Create Room" button (방 생성하기)
            Center(
              child: ElevatedButton(
                onPressed: () async {
                  try {
                    final serverResponse = await createRoom(); // 방 생성 로직
                    if (serverResponse['result'] == 'OK') {
                      final serverResponse1 = serverResponse['response'];
                      if (serverResponse1['result'] == 'OK') {
                        // If success, get roomSeq
                        final roomSeq = serverResponse1['data']['room_seq'];

                        // Success → move to waiting page (방 생성 성공 → 대기 방으로 이동)
                        if (_isTeamGame) {
                          Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(
                              builder: (_) => WaitingRoomTeamPage(
                                roomSeq: roomSeq,
                                roomType: 'team',
                              ),
                            ),
                            (route) => false,
                          );
                        } else {
                          Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(
                              builder: (_) => WaitingRoomPrivatePage(
                                roomSeq: roomSeq,
                                roomType: 'private',
                              ),
                            ),
                            (route) => false,
                          );
                        }
                      } else {
                        showResponseDialog(
                          context,
                          '${serverResponse1['response_info']['msg_title']}',
                          '${serverResponse1['response_info']['msg_content']}',
                        );
                      }
                    } else {
                      showResponseDialog(
                        context,
                        'Room Creation Failed', // '방 생성 실패'
                        'There is a problem with the server. Please contact the administrator.', 
                        // '서버에 문제가 있습니다. 관리자에게 문의해주세요.'
                      );
                    }
                  } catch (e) {
                    showResponseDialog(context, 'Room Creation Failed', e.toString()); 
                    // '방 생성 실패'
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 40),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(40),
                  ),
                ),
                child: const Text(
                  'Create Room', // '방 생성하기'
                  style: TextStyle(fontSize: 16),
                ),
              ),
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  /// "Create Room" logic (“방 생성” 로직)
  Future<Map<String, dynamic>> createRoom() async {
    // Build request body (requestBody 생성)
    final requestBody = {
      'room_title': _roomNameController.text,
      'room_intro': _roomDescriptionController.text,
      'open_yn': _isPrivate ? 'N' : 'Y',
      'room_pw': _isPrivate ? _passwordController.text : '',
      'running_time': _selectedHour.toString(),
      'room_type': _isTeamGame ? 'team' : 'private',
      'number_of_teams': _selectedTeamCount.toString(),
      'number_of_people': _maxParticipantsController.text,
      // Score open range:
      //  solo: 'ALL', 'PRIVATE'
      //  team: 'ALL', 'TEAM', 'PRIVATE'
      'score_open_range': _selectedScoreOpenRange,

      'room_status': 'WAIT',
    };

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

      if (serverResponse == null) {
        throw Exception('Server response is null.');
      }
      if (serverResponse['result'] == 'OK') {
        return serverResponse;
      } else {
        return {'result': 'FAIL'};
      }
    } catch (e) {
      return {'result': 'FAIL'};
    }
  }

  /// White bordered text field (테두리 + 흰 배경 TextField)
  Widget _buildWhiteBorderTextField({
    required TextEditingController controller,
    String hintText = '',
    bool obscureText = false,
  }) {
    return TextField(
      controller: controller,
      obscureText: obscureText,
      style: const TextStyle(color: Colors.black),
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(color: Colors.grey.shade400),
        border: const OutlineInputBorder(),
        filled: true,
        fillColor: Colors.white,
      ),
    );
  }

  /// Multiline text box for introduction, etc. (다중라인 텍스트박스)
  Widget _buildMultilineBox({
    required TextEditingController controller,
    String hintText = '',
  }) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(8),
      ),
      child: TextField(
        controller: controller,
        maxLines: 4,
        style: const TextStyle(color: Colors.black),
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: hintText,
          hintStyle: TextStyle(color: Colors.grey.shade400),
        ),
      ),
    );
  }
}
