import 'dart:async';

import 'package:fis_common/extensions/string.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/auth/auth_board/controller.dart';
import 'package:flyinsono/pages/auth/widgets/form_validator.dart';
import 'package:get/get.dart';

import 'state.dart';

///找回密码界面控制器
class RetrievePasswordController extends FControllerBase {
  static const VERIFICATION_CONTROLLER_TAG = "retrieve_pwd";

  final state = RetrievePasswordState();

  /// 表单编辑状态
  final formEditState = RetrievePasswordFormEditState();

  /// 表单验证状态
  late final formValidateState = RetrievePasswordFormValidateState(state);

  // 文本框控制器
  final accountTextController = TextEditingController();
  final passwordTextController = TextEditingController();
  final reenterPasswordTextController = TextEditingController();
  final verificationCodeTextController = TextEditingController();

  // 文本框焦点
  final accountFocusNode = FocusNode();
  final verificationCodeFocusNode = FocusNode();
  final passwordFocusNode = FocusNode();
  final reenterPasswordFocusNode = FocusNode();

  //  表单验证控制器
  final accountValidatorController = FFormItemValidatorController();
  final passwordValidatorController = FFormItemValidatorController();
  final reenterPasswordValidatorController = FFormItemValidatorController();

  /// 路由返回
  void onRouteBack({bool clearForm = false}) {
    Get.find<AuthBoardController>().changePageByName(RouteNames.Auth.SignIn);
    formEditState.clear();
    if (clearForm) {
      state.reset();
      // 控制器也要清除，不然状态就不一致
      accountTextController.clear();
      verificationCodeTextController.clear();
      passwordTextController.clear();
      reenterPasswordTextController.clear();
    }
  }

  /// 展示账号验证器
  void showAccountValidator() {
    if (state.account.isEmpty) {
      accountValidatorController.resetValidate();
    } else {
      accountValidatorController.validate();
    }
  }

  /// 展示密码验证器
  void showPwdValidator() {
    if (state.password.isEmpty) {
      passwordValidatorController.resetValidate();
    } else {
      passwordValidatorController.validate();
    }
  }

  /// 展示确认密码验证器
  void showReenterPwdValidator() {
    if (state.reenterPassword.isEmpty) {
      reenterPasswordValidatorController.resetValidate();
    } else {
      reenterPasswordValidatorController.validate();
    }
  }

  /// 隐藏表单验证提示
  void hideFormValidator() {
    accountValidatorController.hide();
    passwordValidatorController.hide();
    reenterPasswordValidatorController.hide();
  }

  /// 表单失焦
  void unfocusForm() {
    accountFocusNode.unfocus();
    passwordFocusNode.unfocus();
    reenterPasswordFocusNode.unfocus();
    verificationCodeFocusNode.unfocus();
  }

  /// 监听焦点状态
  void _listenFocusNodes() {
    accountFocusNode.addListener(() {
      if (accountFocusNode.hasFocus) {
        formEditState.accountEdited = true;
        showAccountValidator();
      } else {
        accountValidatorController.hide();
      }
    });
    passwordFocusNode.addListener(() {
      if (passwordFocusNode.hasFocus) {
        formEditState.pwdEdited = true;
        showPwdValidator();
      } else {
        passwordValidatorController.hide();
      }
    });
    reenterPasswordFocusNode.addListener(() {
      if (reenterPasswordFocusNode.hasFocus) {
        formEditState.reenterPwdEdited = true;
        showReenterPwdValidator();
      } else {
        reenterPasswordValidatorController.hide();
      }
    });
    verificationCodeFocusNode.addListener(() {
      if (verificationCodeFocusNode.hasFocus) {
        formEditState.verificationCodeEdited = true;
      }
    });
  }

  /// 释放资源
  void _doDispose() {
    // 释放焦点
    accountFocusNode.dispose();
    passwordFocusNode.dispose();
    reenterPasswordFocusNode.dispose();
    verificationCodeFocusNode.dispose();

    // 释放文本框控制器
    accountTextController.dispose();
    passwordTextController.dispose();
    reenterPasswordTextController.dispose();
    verificationCodeTextController.dispose();

    // 释放表单验证控制器
    accountValidatorController.dispose();
    passwordValidatorController.dispose();
    reenterPasswordValidatorController.dispose();
  }

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

  @override
  void onClose() {
    _doDispose();
    super.onClose();
  }

  bool _validateForm() {
    if (!formValidateState.accountChecked) {
      showAccountValidator();
      return false;
    }
    if (!formValidateState.pwdChecked) {
      showPwdValidator();
      return false;
    }
    if (!formValidateState.reenterPwdChecked) {
      showReenterPwdValidator();
      return false;
    }
    return true;
  }

  /// 提交重置
  Future<void> onSubmit() async {
    final formValid = _validateForm();
    if (!formValid) return;

    state.onSubmit = true;
    hideFormValidator();
    unfocusForm();

    final isMobileAccount = state.account.isChineseMobileNumber;
    bool result = false;
    try {
      if (isMobileAccount) {
        result = await rpc.login.retrievePasswordByPhoneAsync(
          RetrievePasswordByPhoneRequest(
            phone: state.account,
            verifyCode: state.verificationCode,
            newPassword: FEncryptHelper.symmetryEncrypt(state.password),
          ),
        );
      } else {
        result = await rpc.login.retrievePasswordByEmailAsync(
          RetrievePasswordByEmailRequest(
            mail: state.account,
            verifyCode: state.verificationCode,
            newPassword: FEncryptHelper.symmetryEncrypt(state.password),
          ),
        );
      }
      if (result) {
        // TODO: remember account
        state.onSubmit = false;
        PromptBox.toast(i18nBook.auth.toast4ResetSuccess.t);
        return onRouteBack(clearForm: true);
      }
    } catch (e) {
      logger.e(
          "Reset pwd: send ${isMobileAccount ? 'message' : 'email'} verify code error",
          e);
    }
    state.onSubmit = false;
  }

  /// 获取验证码
  Future<bool> onFetchCodeClick() async {
    final account = state.account;
    bool canSend = false;
    if (account.isNotEmpty) {
      if (i18nBook.isCurrentChinese) {
        canSend = account.isEmail || account.isChineseMobileNumber;
      } else {
        canSend = account.isEmail;
      }
    }
    if (!canSend) {
      formEditState.accountEdited = true;
      PromptBox.toast(i18nBook.auth.toast4AccountDouble.t);
      return false;
    }

    hideFormValidator();
    unfocusForm();

    setBusy(i18nBook.auth.sendingVerificationCode.t);
    final isMobileAccount = account.isChineseMobileNumber;
    bool valid = false;
    try {
      if (isMobileAccount) {
        valid = await rpc.login.sendSMSVerificationCodeAsync(
          SendSMSVerificationCodeRequest(userPhone: account),
        );
      } else {
        valid = await rpc.login.sendEmailVerificationCodeAsync(
          SendEmailVerificationCodeRequest(
              emailAddress: account,
              languageCode: i18nBook.locale.toCodeString('-')),
        );
      }
      if (valid) {
        PromptBox.toast(i18nBook.auth.toast4VerifyCodeSendSuccess.t);
        return true;
      }
    } catch (e) {
      logger.e(
          "Reset pwd: send ${isMobileAccount ? 'message' : 'email'} verify code error",
          e);
      PromptBox.toast(i18nBook.auth.toast4VerifyCodeSendFail.t);
    }

    busy = false;
    return false;
  }
}
