import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // http 패키지 임포트
import 'dart:convert'; // JSON 변환을 위해 임포트
import 'login_page.dart'; // 로그인 페이지 임포트 추가
import 'dart:convert' show utf8; // UTF-8 디코딩을 위해 임포트
import 'package:crypto/crypto.dart'; // crypto 패키지 임포트
import '../../config/config.dart'; // config 패키지 임포트
import '../../dialogs/response_dialog.dart';
import '../../plugins/api.dart';

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

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

class _SignUpPageState extends State<SignUpPage> {
  // 체크박스 상태 (개인정보 수집 동의)
  bool _isAgreed = false; 
  // 입력값 
  String _username = '', _password = '', _confirmPassword = '', _nickname = '', _email = '';
  String _department = '', _introduceMyself = ''; 
  // 오류 메시지 (유효성 검사)
  String? _usernameError, _passwordError, _confirmPasswordError, _nicknameError, _emailError;

  // Scale factor for font size (폰트 크기 조절 스케일 인자)
  double scaleFactor = 1.0;

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

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

  // 유효성 검사 (아이디, 비밀번호, 이메일, 닉네임)
  bool _isUsernameValid(String username) =>
      RegExp(r'^(?![0-9])[A-Za-z0-9]{6,20}$').hasMatch(username);
  bool _isPasswordValidPattern(String password) =>
      RegExp(r"""^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_\-+=~`{}\[\]|\\:;\"'<>,.?/]{8,20}$""")
          .hasMatch(password);
  bool _isEmailValid(String email) =>
      RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  bool _isNicknameValid(String nickname) =>
      RegExp(r'^[A-Za-z가-힣0-9\s]{2,20}$').hasMatch(nickname);

  // label에 따른 입력값 검사
  void _validateInput(String label) {
    setState(() {
      if (label == 'Username') { // '아이디'
        _usernameError = _isUsernameValid(_username)
            ? null
            : 'Nickname must be 2–20 characters, letters and digits. Spaces are also allowed';
      } else if (label == 'Password') { // '비밀번호'
        _passwordError = _isPasswordValidPattern(_password)
            ? null
            : 'Password must be 8–20 characters, including letters and digits.';
      } else if (label == 'Confirm Password') { // '비밀번호 확인'
        _confirmPasswordError = (_password == _confirmPassword)
            ? null
            : 'Passwords do not match.';
      } else if (label == 'Nickname') { // '닉네임'
        _nicknameError = _isNicknameValid(_nickname)
            ? null
            : '* Nickname must be 2–20 characters (letters, Korean, digits).';
      } else if (label == 'Email') { // '이메일'
        _emailError = _isEmailValid(_email)
            ? null
            : (_email.isNotEmpty ? 'Please enter a valid email address.' : null);
      }
    });
  }

  // 회원가입 요청 (Sign-up request)
  Future<void> _signUp() async {
    // 체크박스 상태에 따라 mandatory_terms_yn 값 설정
    final mandatoryTermsYn = _isAgreed ? 'Y' : 'N';
    // 비밀번호 해싱 (SHA-256)
    final hashedPassword = _hashPassword(_password);

    final body = {
      "user_id": _username,
      "user_pw": hashedPassword,
      "nickname": _nickname,
      "user_email": _email,
      "department": _department,
      "introduce_myself": _introduceMyself,
      "mandatory_terms_yn": mandatoryTermsYn
    };

    try {
      final serverResponse = await Api.serverRequest(uri: '/user/signup', body: body);
      Navigator.of(context).pop();

      if (serverResponse == null) {
        showResponseDialog(
          context, 
          'Sign-up Failed' /* 회원가입 실패 */, 
          'No response from server.' /* 서버 응답이 없습니다. */
        );
      }

      if (serverResponse['result'] == 'OK') {
        final serverResponse1 = serverResponse['response'];
        if (serverResponse1['result'] == 'OK') {
          // 성공
          showResponseDialog(
            context, 
            'Sign-up Success' /* 회원가입 성공 */, 
            'Your account has been created successfully.'
            /* 계정이 성공적으로 생성되었습니다. */
          );
        } else {
          showResponseDialog(
            context, 
            serverResponse1['response_info']['msg_title'] /* 회원가입 실패 */, 
            serverResponse1['response_info']['msg_content'] /* 계정 생성 실패 */
          );
        }
      } else {
        showResponseDialog(
          context, 
          'Sign-up Failed' /* 회원가입 실패 */, 
          'Failed to create an account.' /* 계정 생성 실패 */
        );
      }
    } catch (e) {
      Navigator.of(context).pop();
      showResponseDialog(
        context, 
        'Error' /* 오류 */, 
        'Request failed. Please contact the administrator.'
        /* 요청이 실패했습니다. 관리자에게 문의해주세요. */
      );
    }
  }

  // 비밀번호 해싱 (SHA-256)
  String _hashPassword(String password) {
    final bytes = utf8.encode(password);
    final digest = sha256.convert(bytes);
    return digest.toString();
  }

  // 입력필드 공용 위젯 (label에 따라 유효성 검사)
  Widget _buildTextField(String label, Function(String) onChanged, {
    bool obscureText = false,
    String? errorText,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextField(
          onChanged: (value) {
            onChanged(value);
            _validateInput(label);
          },
          obscureText: obscureText,
          decoration: InputDecoration(
            labelText: label,
            labelStyle: const TextStyle(color: Colors.black),
            border: const OutlineInputBorder(),
            focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.black, width: 2.0),
            ),
            errorStyle: const TextStyle(color: Colors.red, fontSize: 12),
          ),
        ),
        if (errorText != null)
          Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Text(errorText, style: const TextStyle(color: Colors.red, fontSize: 12)),
          ),
        const SizedBox(height: 16),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('ALL SCORE', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, color: Colors.white),
          onPressed: () => Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const LoginPage()), (route) => false),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const Text(
                'Sign Up', // '회원가입'
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black),
              ),
              const SizedBox(height: 32),

              _buildTextField('Username', (value) => _username = value, errorText: _usernameError),
              _buildTextField('Password', (value) => _password = value, obscureText: true, errorText: _passwordError),
              _buildTextField('Confirm Password', (value) => _confirmPassword = value, obscureText: true, errorText: _confirmPasswordError),
              _buildTextField('Nickname', (value) => _nickname = value, errorText: _nicknameError),
              _buildTextField('Email', (value) => _email = value, errorText: _emailError),
              _buildTextField('Affiliation (Optional)', (value) => _department = value),
              _buildTextField('Self-introduction (Optional)', (value) => _introduceMyself = value),
              const SizedBox(height: 16),

              // 개인정보 수집 및 이용 동의서
              const Text(
                'Consent to the Collection and Use of Personal Information',
                // '개인정보 수집 및 이용 동의서'
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black),
              ),
              const SizedBox(height: 8),
              Container(
                height: 200,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black.withOpacity(0.5)),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Scrollbar(
                  thickness: 5,
                  radius: const Radius.circular(5),
                  child: SingleChildScrollView(
                    child: const Padding(
                      padding: EdgeInsets.all(15.0),
                      child: Text(
                        Config.termsOfService,
                        textAlign: TextAlign.left,
                        style: const TextStyle(color: Colors.black),
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              // 동의 체크박스
              Row(
                children: [
                  Transform.scale(
                    scale: scaleFactor,
                    child: Checkbox(
                      value: _isAgreed,
                      onChanged: (value) {
                        setState(() {
                          _isAgreed = value ?? false;
                        });
                      },
                    ),
                  ),
                  // Checkbox와 텍스트 사이 간격
                  const SizedBox(width: 8),
                  
                  // Expanded로 Text 감싸기
                  Expanded(
                    child: Text(
                      'I agree to the collection and use of my personal information.',
                      style: const TextStyle(fontSize: 12),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      // softWrap: true,  // 기본값이 true이므로 생략 가능
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: _signUp, 
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.black,
                  foregroundColor: Colors.white,
                ),
                child: const Text('Sign Up for ALLSCORE'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
