import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../config/translations/strings_enum.dart';
import '../../../constants/enums.dart';
import '../../../controllers/api_controller.dart';
import '../../../dialog/loading/loading_dialog.dart';
import '../../../routes/app_pages.dart';

class SignupController extends GetxController {
  final _apiController = Get.find<ApiController>();
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final usernameFocusNode = FocusNode();
  final passwordFocusNode = FocusNode();
  final _isSignup = false.obs;
  bool get isSignup => _isSignup.value;
  set isSignup(bool value) {
    _isSignup.value = value;
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    usernameFocusNode.dispose();
    passwordFocusNode.dispose();
    super.onClose();
  }

  void checkSignup() {
    final username = usernameController.text;
    final password = passwordController.text;
    if (validatorInputValue(username) && validatorInputValue(password)) {
      isSignup = true;
    } else {
      isSignup = false;
    }
  }

  //6-20 characters (letters or numbers)
  bool validatorInputValue(String value) {
    // 只允许字母和数字并且是6-20位
    return value.length >= 6 &&
        value.length <= 20 &&
        RegExp(r'^[a-zA-Z0-9]+$').hasMatch(value);
  }

  // 处理注册
  Future<void> handleSignUp() async {
    if (!isSignup) {
      return;
    }
    final params = {
      "account": usernameController.text.trim(),
      "password": passwordController.text,
      "registMode": RegisterMode.manual.value,
    };
    // 取消输入框焦点，关闭软键盘，防止 LoadingDialog 关闭后软键盘再次弹出
    FocusManager.instance.primaryFocus?.unfocus();
    await LoadingDialog.show(
      context: Get.context!,
      loadingText: Strings.signingUp.tr,
      successText: Strings.signUpSuccessful.tr,
      onRequest: () async {
        // 执行你的异步请求
        await _apiController.register(params);
      },
      onSuccess: () {
        // 成功后的操作
        Get.offAllNamed(Routes.HOME);
      },
    );
  }
}
