import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../../dialogs/response_dialog.dart';
import 'package:crypto/crypto.dart';
import '../../plugins/api.dart';
import '../../plugins/utils.dart';
import 'withdrawal_page.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../config/config.dart';
import '../room/main_page.dart';

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

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

class _MyPageState extends State<MyPage> {
  String user_nickname = '';
  String user_pw = '';
  String new_user_pw = '**********';
  String user_email = '';
  String user_department = '';
  String user_introduce_myself = '';
  String user_profile_image = '';
  bool isEditingNickname = false;
  bool isEditingPassword = false;
  bool isConfirmingPassword = false;
  String confirmPassword = '';
  final TextEditingController _nicknameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();
  final FocusNode _nicknameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  final FocusNode _confirmPasswordFocusNode = FocusNode();
  String? _passwordError;
  String? _emailError;
  final TextEditingController _emailController = TextEditingController();
  final FocusNode _emailFocusNode = FocusNode();
  bool isEditingEmail = false;
  final TextEditingController _departmentController = TextEditingController();
  final FocusNode _departmentFocusNode = FocusNode();
  bool isEditingDepartment = false;
  final TextEditingController _introduceController = TextEditingController();
  String? _nicknameError;
  XFile? _image; // 선택된 이미지 파일
  String _oauthType = 'idpw'; // 로그인 방법

  double scaleFactor = 1.0;
  double buttonScaleFactor = 1.0;

  @override
  void initState() {
    super.initState();
    _introduceController.text = ''; // 초기화
    _fetchUserInfo();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _updateScaleFactor();
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _nicknameFocusNode.dispose();
    _passwordFocusNode.dispose();
    _confirmPasswordFocusNode.dispose();
    _emailController.dispose();
    _emailFocusNode.dispose();
    _departmentController.dispose();
    _departmentFocusNode.dispose();
    _introduceController.dispose();
    super.dispose();
  }

  // 화면 크기에 따라 폰트 크기 조절
  void _updateScaleFactor() {
    final screenWidth = MediaQuery.of(context).size.width;
    const baseWidth = 400.0;
    setState(() {
      scaleFactor = (screenWidth / baseWidth).clamp(0.8, 1.2);
      buttonScaleFactor = (screenWidth / baseWidth).clamp(0.6, 1.2);
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (_) => const MainPage()),
          (route) => false,
        );
        return false;
      },
      child: GestureDetector(
        onTap: () {
          // 화면 아무 곳이나 탭하면 편집 모드 해제
          if (isEditingNickname) {
            setState(() {
              user_nickname = _nicknameController.text;
              isEditingNickname = false;
              _nicknameFocusNode.unfocus();
            });
          }
          if (isEditingPassword) {
            setState(() {
              new_user_pw = _passwordController.text;
              isEditingPassword = false;
              _passwordFocusNode.unfocus();
            });
          }
          if (isConfirmingPassword) {
            setState(() {
              isConfirmingPassword = false;
              _confirmPasswordFocusNode.unfocus();
            });
          }
          if (isEditingEmail) {
            setState(() {
              user_email = _emailController.text;
              isEditingEmail = false;
              _emailFocusNode.unfocus();
            });
          }
          if (isEditingDepartment) {
            setState(() {
              user_department = _departmentController.text;
              isEditingDepartment = false;
              _departmentFocusNode.unfocus();
            });
          }
          FocusScope.of(context).unfocus();
        },
        child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: const Text('My Page', style: TextStyle(color: Colors.black)), // '마이페이지'
            backgroundColor: Colors.transparent,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
              onPressed: () {
                Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(builder: (_) => const MainPage()),
                  (route) => false,
                );
              },
            ),
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 닉네임 카드
                  Card(
                    elevation: 4,
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'Nickname:', // '닉네임:'
                            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                          ),
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  isEditingNickname = true;
                                  _nicknameController.text = user_nickname;
                                  _nicknameFocusNode.requestFocus();
                                });
                              },
                              child: isEditingNickname
                                  ? TextField(
                                      controller: _nicknameController,
                                      focusNode: _nicknameFocusNode,
                                      onChanged: (newNickname) {
                                        setState(() {
                                          user_nickname = newNickname;
                                          // 닉네임 패턴 검증
                                          if (!_isNicknameValidPattern(user_nickname)) {
                                            _nicknameError = 'Nickname must be 2-20 characters (letters, Korean, digits, spaces).'; 
                                            // '닉네임은 2~20자 (영문, 한글, 숫자, 공백)만 허용'
                                          } else {
                                            _nicknameError = null;
                                          }
                                        });
                                      },
                                      onSubmitted: (newNickname) {
                                        setState(() {
                                          user_nickname = newNickname;
                                          isEditingNickname = false;
                                          _nicknameFocusNode.unfocus();
                                        });
                                      },
                                      decoration: const InputDecoration(
                                        hintText: 'Enter your nickname', // '닉네임을 입력하세요'
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                                      ),
                                    )
                                  : Container(
                                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                      child: Text(
                                        user_nickname,
                                        style: const TextStyle(fontSize: 18, color: Colors.black54),
                                      ),
                                    ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  // 닉네임 오류 메시지
                  if (_nicknameError != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: Text(
                        _nicknameError!,
                        style: const TextStyle(color: Colors.red, fontSize: 12),
                      ),
                    ),
                  const SizedBox(height: 16),
                  // 비밀번호 수정 카드 (idpw 로그인만)
                  _oauthType == 'idpw'
                      ? Card(
                          elevation: 4,
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  'Password:', // '비밀번호:'
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        isEditingPassword = true;
                                        // 사용자가 비밀번호를 편집할 때, 기존 값 대신 별표를 표시
                                        _passwordController.text = new_user_pw.replaceAll(RegExp(r'.'), '*');
                                        _passwordFocusNode.requestFocus();
                                      });
                                    },
                                    child: isEditingPassword
                                        ? TextField(
                                            controller: _passwordController,
                                            focusNode: _passwordFocusNode,
                                            obscureText: true,
                                            onChanged: (newPassword) {
                                              setState(() {
                                                new_user_pw = newPassword;
                                                _passwordError = _isPasswordValidPattern(new_user_pw)
                                                    ? null
                                                    : 'Password must be 8-20 characters and include both letters and digits.'; 
                                                    // '비밀번호는 8~20자, 영문과 숫자를 포함해야 함'
                                              });
                                            },
                                            onSubmitted: (newPassword) {
                                              setState(() {
                                                isEditingPassword = false;
                                                _passwordFocusNode.unfocus();
                                              });
                                            },
                                            decoration: const InputDecoration(
                                              hintText: 'Enter your password', // '비밀번호를 입력하세요'
                                              border: InputBorder.none,
                                              contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                                            ),
                                          )
                                        : Container(
                                            padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                            child: const Text(
                                              '**********', // 화면상에 별표로 표시
                                              style: TextStyle(fontSize: 18, color: Colors.black54),
                                            ),
                                          ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      : Card(
                          elevation: 4,
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: const Padding(
                            padding: EdgeInsets.all(16.0),
                            child: Text(
                              'Password: Social login users cannot change the password.', 
                              // '비밀번호: 소셜 로그인 사용자는 변경할 수 없습니다.'
                              style: TextStyle(fontSize: 16, color: Colors.black54),
                            ),
                          ),
                        ),
                  // 비밀번호 오류 메시지
                  if (_oauthType == 'idpw' && _passwordError != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: Text(
                        _passwordError!,
                        style: const TextStyle(color: Colors.red, fontSize: 12),
                      ),
                    ),
                  _oauthType == 'idpw'
                      ? const SizedBox(height: 16)
                      : const SizedBox(),
                  // 비밀번호 확인 (idpw 로그인만)
                  _oauthType == 'idpw'
                      ? Card(
                          elevation: 4,
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  'Confirm Password:', // '비밀번호 확인:'
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        isConfirmingPassword = true;
                                        _confirmPasswordController.text = '';
                                        _confirmPasswordFocusNode.requestFocus();
                                      });
                                    },
                                    child: isConfirmingPassword
                                        ? TextField(
                                            controller: _confirmPasswordController,
                                            focusNode: _confirmPasswordFocusNode,
                                            obscureText: true,
                                            onChanged: (value) {
                                              setState(() {
                                                confirmPassword = value;
                                              });
                                            },
                                            onSubmitted: (newPassword) {
                                              setState(() {
                                                isConfirmingPassword = false;
                                                _confirmPasswordFocusNode.unfocus();
                                              });
                                            },
                                            decoration: const InputDecoration(
                                              hintText: 'Please re-enter your password', 
                                              // '비밀번호를 다시 입력하세요'
                                              border: InputBorder.none,
                                              contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                                            ),
                                          )
                                        : Container(
                                            padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                            child: Text(
                                              '*' * confirmPassword.length, // 입력된 패스워드 길이만큼 별표
                                              style: const TextStyle(fontSize: 18, color: Colors.black54),
                                            ),
                                          ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      : const SizedBox(),
                  if (_oauthType == 'idpw')
                    const SizedBox(height: 8),
                  if (_oauthType == 'idpw')
                    Text(
                      (new_user_pw == confirmPassword)
                          ? 'Passwords match.' // '비밀번호가 일치합니다.'
                          : (confirmPassword.isNotEmpty ? 'Passwords do not match.' : ''), 
                            // '비밀번호가 일치하지 않습니다.'
                      style: TextStyle(
                        fontSize: 16,
                        color: (new_user_pw == confirmPassword) ? Colors.green : Colors.red,
                      ),
                    ),
                  // 이메일 (idpw 로그인 시 수정 가능)
                  _oauthType == 'idpw'
                      ? Card(
                          elevation: 4,
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  'Email:', // '이메일:'
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        isEditingEmail = true;
                                        _emailController.text = user_email;
                                        _emailFocusNode.requestFocus();
                                      });
                                    },
                                    child: isEditingEmail
                                        ? TextField(
                                            controller: _emailController,
                                            focusNode: _emailFocusNode,
                                            onChanged: (value) {
                                              setState(() {
                                                user_email = value;
                                                _emailError = _isEmailValid(user_email)
                                                    ? null
                                                    : 'Please enter a valid email address.'; 
                                                      // '올바른 이메일 주소를 입력하세요'
                                              });
                                            },
                                            onSubmitted: (newEmail) {
                                              setState(() {
                                                user_email = newEmail;
                                                isEditingEmail = false;
                                                _emailFocusNode.unfocus();
                                              });
                                            },
                                            decoration: const InputDecoration(
                                              hintText: 'Enter your email address', 
                                              // '이메일을 입력하세요'
                                              border: InputBorder.none,
                                              contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                                            ),
                                          )
                                        : Container(
                                            padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                            child: Text(
                                              user_email,
                                              style: const TextStyle(fontSize: 18, color: Colors.black54),
                                            ),
                                          ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      : Card(
                          elevation: 4,
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  'Email:', // '이메일:'
                                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                                ),
                                Expanded(
                                  child: Text(
                                    user_email, // 읽기 전용
                                    style: const TextStyle(fontSize: 18, color: Colors.black54),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                  if (_oauthType == 'idpw' && _emailError != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: Text(
                        _emailError!,
                        style: const TextStyle(color: Colors.red, fontSize: 12),
                      ),
                    ),
                  const SizedBox(height: 8),
                  // 소속(Department)
                  Card(
                    elevation: 4,
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'Department:', // '소속:'
                            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                          ),
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  isEditingDepartment = true;
                                  _departmentController.text = user_department;
                                  _departmentFocusNode.requestFocus();
                                });
                              },
                              child: isEditingDepartment
                                  ? TextField(
                                      controller: _departmentController,
                                      focusNode: _departmentFocusNode,
                                      onChanged: (value) {
                                        setState(() {
                                          user_department = value;
                                        });
                                      },
                                      onSubmitted: (newDepartment) {
                                        setState(() {
                                          user_department = newDepartment;
                                          isEditingDepartment = false;
                                          _departmentFocusNode.unfocus();
                                        });
                                      },
                                      decoration: const InputDecoration(
                                        hintText: 'Enter your department', // '소속을 입력하세요'
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
                                      ),
                                    )
                                  : Container(
                                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                      child: Text(
                                        user_department,
                                        style: const TextStyle(fontSize: 18, color: Colors.black54),
                                      ),
                                    ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  const SizedBox(height: 8),
                  const Text(
                    'Please set your profile image.', // '프로필 이미지를 설정해주세요.'
                    style: TextStyle(fontSize: 16, color: Colors.black),
                  ),
                  const SizedBox(height: 16),
                  Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        GestureDetector(
                          onTap: () {
                            _selectImage();
                          },
                          child: Container(
                            width: 100,
                            height: 100,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(color: Colors.black),
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(20),
                              child: Image.network(
                                '${Config.baseUrl}/images$user_profile_image',
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return const Center(
                                    child: Text('Unable to load image.'), 
                                    // '이미지를 불러올 수 없습니다.'
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(height: 8),
                        const Text(
                          'Tap the image to select a new one.', // '이미지를 클릭하면 새로 등록할 수 있습니다.'
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 12, color: Colors.blueGrey),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    'Introduce yourself to other users.', // '다른 유저에게 자신을 소개해주세요.'
                    style: TextStyle(fontSize: 16, color: Colors.black),
                  ),
                  const SizedBox(height: 8),
                  TextField(
                    controller: _introduceController,
                    maxLines: 5,
                    decoration: InputDecoration(
                      hintText: 'Write something about yourself...', // '자기소개를 작성하세요...'
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: Colors.black),
                      ),
                      contentPadding: const EdgeInsets.all(10),
                    ),
                    onChanged: (value) {
                      setState(() {
                        user_introduce_myself = value;
                      });
                    },
                  ),
                  const SizedBox(height: 30),
                  Center(
                    child: OutlinedButton(
                      onPressed: () {
                        _showEditDialog();
                      },
                      style: OutlinedButton.styleFrom(
                        backgroundColor: Colors.white,
                        side: const BorderSide(color: Colors.black54, width: 1),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40),
                        ),
                        padding: EdgeInsets.symmetric(
                          vertical: 12 * scaleFactor,
                          horizontal: 60 * scaleFactor,
                        ),
                      ),
                      child: const Text(
                        'Update', // '수정하기'
                        style: TextStyle(color: Colors.black, fontSize: 16),
                      ),
                    ),
                  ),
                  const SizedBox(height: 10),
                  Center(
                    child: OutlinedButton(
                      onPressed: () {
                        // 회원탈퇴 페이지
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => const WithdrawalPage()),
                        );
                      },
                      style: OutlinedButton.styleFrom(
                        backgroundColor: Colors.white,
                        side: const BorderSide(color: Colors.black54, width: 1),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40),
                        ),
                        padding: EdgeInsets.symmetric(
                          vertical: 12 * scaleFactor,
                          horizontal: 60 * scaleFactor,
                        ),
                      ),
                      child: const Text(
                        'Delete Account', // '회원탈퇴'
                        style: TextStyle(color: Colors.black, fontSize: 16),
                      ),
                    ),
                  ),
                  const SizedBox(height: 30),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _fetchUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? authToken = prefs.getString('auth_token');
    setState(() {
      _oauthType = prefs.getString('oauth_type') ?? 'idpw';
    });

    final response = await Api.serverRequest(
      uri: '/user/myinfo',
      body: {},
    );

    if (response['result'] == 'OK') {
      final jsonResponse = response['response'];
      if (jsonResponse['result'] == 'OK') {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('auth_token', jsonResponse['auth']['token']);

        setState(() {
          user_nickname = jsonResponse['data']['nickname'];
          user_email = jsonResponse['data']['user_email'];
          user_department = jsonResponse['data']['department'];
          user_introduce_myself = jsonResponse['data']['introduce_myself'];
          user_profile_image = jsonResponse['data']['profile_img'];
          _introduceController.text = user_introduce_myself;
        });
      } else {
        showResponseDialog(
          context,
          '${jsonResponse['response_info']['msg_title']}',
          '${jsonResponse['response_info']['msg_content']}',
        );
      }
    } else {
      showResponseDialog(
        context,
        'Request Failed', // '요청 실패'
        'There is a problem with the server. Please contact the administrator.', 
        // '서버에 문제가 있습니다. 관리자에게 문의해주세요.'
      );
    }
  }

  bool _isPasswordValidPattern(String password) {
    // 비밀번호는 8~20자, 영문과 숫자 필수
    return password.length >= 8 &&
        password.length <= 20 &&
        RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{8,20}$').hasMatch(password);
  }

  bool _isEmailValid(String email) {
    // 이메일 형식 검증
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }

  Future<void> _selectImage() async {
    // 프로필 이미지를 선택하는 다이얼로그
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
            ),
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  'Select Profile Image', // '프로필 이미지 선택'
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                          _pickImage(); // 갤러리에서 이미지 선택
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          side: const BorderSide(color: Colors.black),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text(
                          'Gallery', // '갤러리'
                          style: TextStyle(color: Colors.black),
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          side: const BorderSide(color: Colors.black),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text(
                          'Cancel', // '취소'
                          style: TextStyle(color: Colors.black),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    ).then((pickedFile) {
      if (pickedFile != null) {
        if (pickedFile == 'gallery') {
          _pickImage();
        }
      }
    });
  }

  void _showEditDialog() {
    // 회원정보 수정 전 검증 로직

    // 1) 비밀번호 패턴 검증 (idpw 로그인만)
    if (_oauthType == 'idpw') {
      // 새 비밀번호가 바뀌었을 경우에만 확인
      if (new_user_pw != '**********') {
        if (!_isPasswordValidPattern(new_user_pw)) {
          showResponseDialog(context, 'Update Failed', 'Please check the password pattern.'); 
          // '수정 실패', '비밀번호 패턴을 확인해주세요.'
          return;
        }
        if (new_user_pw != confirmPassword) {
          showResponseDialog(context, 'Update Failed', 'Passwords do not match.'); 
          // '수정 실패', '비밀번호가 일치하지 않습니다.'
          return;
        }
      }
    }

    // 2) 이메일/닉네임 패턴 검증
    if (!_isEmailValid(user_email)) {
      showResponseDialog(context, 'Update Failed', 'Please check email format.');
      // '수정 실패', '이메일 형식을 확인해주세요.'
      return;
    }
    if (!_isNicknameValidPattern(user_nickname)) {
      showResponseDialog(context, 'Update Failed', 'Please check nickname pattern.');
      // '수정 실패', '닉네임 패턴을 확인해주세요.'
      return;
    }

    // 회원정보 수정 모달창
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          title: Center(
            child: Text(
              'Update Profile', // '회원정보 수정'
              style: TextStyle(fontSize: 20 * scaleFactor, fontWeight: FontWeight.bold),
            ),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Center(
                child: Text(
                  'Update your information.', // '회원정보를 수정합니다.'
                  style: TextStyle(fontSize: 16 * scaleFactor),
                ),
              ),
              const SizedBox(height: 8),
              if (_oauthType == 'idpw') ...[
                Center(
                  child: Text(
                    'Please enter your current password.', 
                    // '현재 비밀번호를 입력해주세요.'
                    style: TextStyle(fontSize: 16 * scaleFactor),
                  ),
                ),
                const SizedBox(height: 8),
                TextField(
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: 'Current password', // '현재 비밀번호'
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                    contentPadding: const EdgeInsets.all(10),
                  ),
                  onChanged: (value) {
                    user_pw = value;
                  },
                ),
              ],
            ],
          ),
          actions: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                SizedBox(
                  width: 100 * buttonScaleFactor,
                  child: ElevatedButton(
                    onPressed: () async {
                      try {
                        final serverResponse = await _updateUserInfo();
                        if (serverResponse['result'] == 'OK') {
                          final serverResponse1 = serverResponse['response'];
                          if (serverResponse1['result'] == 'OK') {
                            await showResponseDialog(
                              context, 
                              'Update Successful', // '수정 성공'
                              'Your information has been successfully updated.' 
                              // '회원정보가 성공적으로 수정되었습니다.'
                            );
                            Navigator.pushAndRemoveUntil(
                              context,
                              MaterialPageRoute(builder: (context) => const MyPage()),
                              (route) => false,
                            );
                          } else {
                            await showResponseDialog(
                              context,
                              '${serverResponse1['response_info']['msg_title']}',
                              '${serverResponse1['response_info']['msg_content']}',
                            );
                          }
                        } else {
                          await showResponseDialog(
                            context,
                            'Update Failed', // '수정 실패'
                            'There is a problem with the server. Please contact the administrator.' 
                            // '서버에 문제가 있습니다. 관리자에게 문의해주세요.'
                          );
                        }
                      } catch (e) {
                        await showResponseDialog(
                          context, 
                          'Update Failed', // '수정 실패'
                          e.toString()
                        );
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      side: const BorderSide(color: Colors.black54, width: 1),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(40),
                      ),
                    ),
                    child: Text(
                      'Update', // '수정'
                      style: TextStyle(color: Colors.black, fontSize: 14 * buttonScaleFactor),
                    ),
                  ),
                ),
                SizedBox(
                  width: 100 * buttonScaleFactor,
                  child: ElevatedButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      side: const BorderSide(color: Colors.black54, width: 1),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(40),
                      ),
                    ),
                    child: Text(
                      'Cancel', // '취소'
                      style: TextStyle(color: Colors.black, fontSize: 14 * buttonScaleFactor),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  Future<Map<String, dynamic>> _updateUserInfo() async {
    try {
      final serverResponse = await Api.serverRequest(
        uri: '/user/update/user/info',
        body: {
          "user_pw": Utils.hashPassword(user_pw),
          "new_user_pw": Utils.hashPassword(new_user_pw),
          "user_pw_change_yn": new_user_pw != '**********' ? 'Y' : 'N',
          "nickname": user_nickname,
          "user_email": user_email,
          "department": user_department,
          "profile_img": user_profile_image,
          "introduce_myself": user_introduce_myself,
          "oauth_type": _oauthType,
        },
      );

      if (serverResponse == null) {
        throw Exception('Server response is null.');
      }

      if (serverResponse['result'] == 'OK') {
        return serverResponse;
      } else {
        return {'result': 'FAIL'};
      }
    } catch (e) {
      return {'result': 'FAIL'};
    }
  }

  bool _isNicknameValidPattern(String nickname) {
    // 닉네임은 2~20자, 영문/한글/숫자/공백 가능
    return RegExp(r'^[A-Za-z가-힣0-9\s]{2,20}$').hasMatch(nickname);
  }

  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? selectedImage = await picker.pickImage(source: ImageSource.gallery);

    if (selectedImage != null) {
      final serverResponse = await Api.uploadProfileImage(selectedImage, body: {
        'test': 'test',
      });

      if (serverResponse['result'] == 'OK') {
        final serverResponse1 = serverResponse['response'];
        if (serverResponse1['result'] == 'OK') {
          await showResponseDialog(
            context,
            'Upload Successful', // '업로드 성공'
            'Profile image uploaded successfully.', 
            // '프로필 이미지가 성공적으로 업로드되었습니다.'
          );
          setState(() {
            // user_profile_image 값을 업데이트 (앞의 '/images' 제거)
            user_profile_image = serverResponse1['data']['img_src']
                .replaceFirst('/images', '');
          });
        } else {
          await showResponseDialog(
            context,
            '${serverResponse1['response_info']['msg_title']}',
            '${serverResponse1['response_info']['msg_content']}',
          );
        }
      } else {
        await showResponseDialog(
          context,
          'Upload Failed', // '업로드 실패'
          'There is a problem with the server. Please contact the administrator.',
          // '서버에 문제가 있습니다. 관리자에게 문의해주세요.'
        );
      }
    }
  }
}
