import 'package:flutter/material.dart';
import '../plugins/api.dart';       // server requests (서버 요청)
import 'response_dialog.dart';     // response modal etc. (응답 모달 etc)

class ScoreEditDialog extends StatefulWidget {
  final int roomSeq;           // 방 번호
  final String roomType;       // "PRIVATE" or "TEAM"
  final Map<String, dynamic> userData;  // 유저 데이터

  const ScoreEditDialog({
    Key? key,
    required this.roomSeq,
    required this.roomType,
    required this.userData,
  }) : super(key: key);

  @override
  State<ScoreEditDialog> createState() => _ScoreEditDialogState();
}

class _ScoreEditDialogState extends State<ScoreEditDialog> {
  late int currentScore; // 현재 점수
  late int newScore;     // 수정 후 점수

  @override
  void initState() {
    super.initState();
    currentScore = (widget.userData['score'] ?? 0) as int;
    newScore = currentScore;
  }

  Future<void> _onApplyScore() async {
    // Apply the score changes (점수 수정 적용)
    final reqBody = {
      "room_seq": "${widget.roomSeq}",
      "room_type": widget.roomType,
      "target_user_seq": "${widget.userData['user_seq']}",
      "after_score": "$newScore",
    };

    try {
      final response = await Api.serverRequest(
        uri: '/room/score/update/score',
        body: reqBody,
      );
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          // success (성공)
          await showResponseDialog(
            context, 
            'Success',  // '성공'
            'Score has been updated.' // '점수가 업데이트되었습니다.'
          );
          Navigator.pop(context, 'refresh');
        } else {
          final msgTitle = resp['response_info']?['msg_title'] ?? 'Error'; 
          // '오류'
          final msgContent = resp['response_info']?['msg_content'] ?? 'Score update failed'; 
          // '점수 업데이트 실패'
          showResponseDialog(context, msgTitle, msgContent);
        }
      } else {
        showResponseDialog(
          context, 
          'Failed', // '실패'
          'Server communication failed.' // '서버 통신 실패'
        );
      }
    } catch (e) {
      showResponseDialog(
        context, 
        'Error occurred', 
        // '오류 발생'
        '$e'
      );
    }
  }

  void _onDelta(int delta) {
    // Increase or decrease the new score (점수 증감)
    setState(() {
      newScore += delta;
      // Arbitrary maximum/minimum (임의 최대/최소)
      if (newScore > 999999) newScore = 999999;
      if (newScore < -999999) newScore = -999999;
    });
  }

  @override
  Widget build(BuildContext context) {
    final userName = widget.userData['nickname'] ?? 'User'; 
    // '유저'
    final department = widget.userData['department'] ?? ''; 
    // '소속정보'
    final introduce = widget.userData['introduce_myself'] ?? ''; 
    // '소개글'

    return Dialog(
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'View User Info', 
              // '유저 정보 보기'
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),

            // Nickname & Department (닉네임 + 소속)
            Text(
              userName, 
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            Text(
              department,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),

            const SizedBox(height: 12),

            // Introduction (소개)
            const Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Introduction', 
                // '소개글'
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 4),
            Container(
              width: double.infinity,
              height: 80,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
                borderRadius: BorderRadius.circular(8),
              ),
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(8),
                child: Text(
                  introduce.isNotEmpty 
                      ? introduce 
                      : 'No introduction.', 
                  // '소개글이 없습니다.'
                ),
              ),
            ),

            const SizedBox(height: 12),

            // Score editing area (점수 수정 영역)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '$currentScore',
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const Text(' → '),
                Text(
                  '$newScore',
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 8),

            SizedBox(
              child: GridView.count(
                crossAxisCount: 2, 
                mainAxisSpacing: 8,
                crossAxisSpacing: 12,
                childAspectRatio: 3.0,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  _buildDeltaButton(-100),
                  _buildDeltaButton(100),
                  _buildDeltaButton(-10),
                  _buildDeltaButton(10),
                  _buildDeltaButton(-1),
                  _buildDeltaButton(1),
                ],
              ),
            ),

            const SizedBox(height: 12),

            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _onApplyScore,
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.black),
                  child: const Text(
                    'Apply', 
                    // '적용'
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.black),
                  child: const Text(
                    'Close', 
                    // '닫기'
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDeltaButton(int delta) {
    final label = (delta >= 0) ? '+$delta' : '$delta';
    return SizedBox(
      width: 50,
      height: 30,
      child: ElevatedButton(
        onPressed: () => _onDelta(delta),
        style: ElevatedButton.styleFrom(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        side: const BorderSide(color: Colors.black),
      ),
        child: Text(label),
      ),
    );
  }
}
