import 'package:flutter/material.dart';
import 'response_dialog.dart'; // 사용 예시로 임포트
import '../../plugins/api.dart'; // 사용 예시로 임포트

class TeamNameEditModal extends StatefulWidget {
  final int roomSeq;                 
  // 방 번호
  final String roomTypeName;         
  // "TEAM"
  final String beforeTeamName;       
  // 현재 팀명
  final List<String> existingTeamNames; 
  // 이미 존재하는 팀명 (ex: ["A","B","C","WAIT"] 등)

  const TeamNameEditModal({
    Key? key,
    required this.roomSeq,
    required this.roomTypeName,
    required this.beforeTeamName,
    required this.existingTeamNames,
  }) : super(key: key);

  @override
  State<TeamNameEditModal> createState() => _TeamNameEditModalState();
}

class _TeamNameEditModalState extends State<TeamNameEditModal> {
  String afterTeamName = '';
  // 새 팀명
  String _errorMsg = ''; 
  // 오류 메시지 (중복 등)

  Future<void> _onUpdateTeamName() async {
    final newName = afterTeamName.trim().toUpperCase();

    // If new name is empty or same as old name (새 팀명이 비었거나 기존 팀명과 같으면 처리)
    if (newName.isEmpty) {
      setState(() {
        _errorMsg = 'Please enter a new team name.'; 
        // '새 팀명을 입력해주세요.'
      });
      return;
    }

    // Check duplication (중복 검사)
    final existingNames = widget.existingTeamNames.map((e) => e.toUpperCase()).toList();
    if (newName != widget.beforeTeamName.toUpperCase() && existingNames.contains(newName)) {
      setState(() {
        _errorMsg = 'Team name already exists.'; 
        // '이미 존재하는 팀명입니다.'
      });
      return;
    }

    // Request body (서버 요청)
    // {
    //   "room_seq": "9",
    //   "room_type_name": "TEAM",
    //   "before_team_name": "A",
    //   "after_team_name": "B"
    // }
    final reqBody = {
      'room_seq': '${widget.roomSeq}',
      'room_type_name': widget.roomTypeName, 
      'before_team_name': widget.beforeTeamName,
      'after_team_name': newName,
    };

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/update/team/name',
        body: reqBody,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          // Success (성공)
          await showResponseDialog(context, 'Success' /* '성공' */, 'Team name 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');
    }
  }

  @override
  Widget build(BuildContext context) {
    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(
              'Edit Team Name'
              // '팀명 수정'
              ,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            Text(
              'Current team name: ${widget.beforeTeamName}'
              // '기존 팀명: ${widget.beforeTeamName}'
            ),
            const SizedBox(height: 8),
            TextField(
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'New Team Name'
                // '새 팀명'
              ),
              onChanged: (val) {
                setState(() {
                  afterTeamName = val;
                  _errorMsg = '';
                });
              },
            ),
            // Error message (에러 메시지)
            if (_errorMsg.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                _errorMsg,
                style: const TextStyle(color: Colors.red),
              ),
            ],
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                SizedBox(
                  width: 80,
                  child: ElevatedButton(
                    onPressed: _onUpdateTeamName,
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                    child: const Text(
                      'Update' 
                      // '수정'
                      ,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                SizedBox(
                  width: 80,
                  child: ElevatedButton(
                    onPressed: () => Navigator.pop(context),
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.black, padding: EdgeInsets.zero, minimumSize: Size(0, 30), tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                    child: const Text(
                      'Cancel'
                      // '취소'
                      ,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
