import 'dart:async';

import 'package:cpt_profile/modules/reset_password/reset_password_state.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/auth_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/dialog/verify_code_dialog.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

part 'reset_password_view_model.g.dart';

@riverpod
class ResetPasswordViewModel extends _$ResetPasswordViewModel {
  late final AuthRepository authRepository;

  @override
  ResetPasswordState build() {
    authRepository = ref.read(authRepositoryProvider);

    final state = ResetPasswordState();
    initListener(state);
    ref.onDispose(() {
      onDispose(state);
    });
    return state;
  }

  /// 提交重置密码请求
  void submitResetPassword() async {
    state = state.copyWith(codeErrorText: null, passwordErrorText: null, confirmPasswordErrorText: null);

    final FocusNode phoneFocusNode = state.formData['phone']!['focusNode'];
    final FocusNode codeFocusNode = state.formData['code']!['focusNode'];
    final FocusNode passwordFocusNode = state.formData['password']!['focusNode'];
    final FocusNode confirmPasswordFocusNode = state.formData['confirm_password']!['focusNode'];

    final TextEditingController phoneController = state.formData['phone']!['controller'];
    final TextEditingController codeController = state.formData['code']!['controller'];
    final TextEditingController passwordController = state.formData['password']!['controller'];
    final TextEditingController confirmPasswordController = state.formData['confirm_password']!['controller'];

    phoneFocusNode.unfocus();
    codeFocusNode.unfocus();
    passwordFocusNode.unfocus();
    confirmPasswordFocusNode.unfocus();

    final phone = phoneController.text;
    final code = codeController.text;
    final password = passwordController.text;
    final confirmPassword = confirmPasswordController.text;

    Log.d('当前待提交的 phone:$phone code:$code password:$password confirmPassword:$confirmPassword');

    if (Utils.isEmpty(phone)) {
      ToastEngine.show("Mobile Phone Error");
      return;
    }

    if (Utils.isEmpty(code)) {
      state = state.copyWith(codeErrorText: "Verification Code cannot be empty!");
      return;
    }

    if (Utils.isEmpty(password)) {
      state = state.copyWith(passwordErrorText: "Password cannot be empty!");
      return;
    }

    if (Utils.isEmpty(confirmPassword)) {
      state = state.copyWith(confirmPasswordErrorText: "Confirm Password cannot be empty!");
      return;
    }

    if (confirmPassword != password) {
      state = state.copyWith(confirmPasswordErrorText: "Password mismatch, please check password");
      return;
    }

    //执行密码登录
    final result = await authRepository.resetPassword(smsCode: code, password: password, confirmPassword: confirmPassword);

    if (result.isSuccess) {
      //提示成功
      NotifyEngine.showSuccess(S.current.successful);
      //清除用户登录信息
      UserConfigService.getInstance().handleLogoutParams();
      //去登录页面
      ComponentServiceManager().authService.startAndPopAllLoginPage();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //切换隐藏显示密码
  void switchPwdVisibility() {
    state = state.copyWith(pwdVisibility: !state.pwdVisibility);
  }

  void switchConfirmPwdVisibility() {
    state = state.copyWith(confirmPwdVisibility: !state.confirmPwdVisibility);
  }

  void showVerifyCodedDialog() {
    final TextEditingController phoneController = state.formData['phone']!['controller'];
    final phone = phoneController.text;
    if (Utils.isEmpty(phone)) {
      ToastEngine.show("Mobile Phone Error");
      return;
    }

    //短信验证码之前的图片验证码弹窗
    DialogEngine.show(
      onDismiss: () {},
      widget: VerifyCodeDialog(
        confirmAction: (key, code) {
          //发送短信验证码
          _sendSMS(phone, key, code);
        },
      ),
    );
  }

  /// 调用接口发送短信验证码
  void _sendSMS(String phone, String? key, String? code) async {
    final result = await authRepository.sendSMS(
      countryCode: UserConfigService.getState().user?.information?.countryCode ?? "+65",
      phone: phone,
      captchaKey: key,
      captchaValue: code,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess(S.current.send_sms_successful);
      _startCountDown();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  Timer? countdownTimer;

  /// 开启倒计时
  void _startCountDown() {
    //60秒倒计时
    state = state.copyWith(isCounting: true, countdownTime: 60);

    //每秒的倒计时
    countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      int time = state.countdownTime;
      Log.d('倒计时-->$time');
      if (time > 0) {
        time--;
        state = state.copyWith(isCounting: true, countdownTime: time);
      } else {
        state = state.copyWith(isCounting: false, countdownTime: 0);
        countdownTimer?.cancel(); // 取消计时器
      }
    });
  }

  //初始化监听
  void initListener(ResetPasswordState initState) {
    final String? phone = UserConfigService.getState().user?.information?.phone;
    final TextEditingController phoneController = initState.formData['phone']!['controller'];
    phoneController.text = phone ?? "-";

    final FocusNode codeFocusNode = initState.formData['code']!['focusNode'];
    final FocusNode passwordFocusNode = initState.formData['password']!['focusNode'];
    final FocusNode confirmPasswordFocusNode = initState.formData['confirm_password']!['focusNode'];

    codeFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (codeFocusNode.hasFocus) {
        state = state.copyWith(codeErrorText: null);
      }
    });

    passwordFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (passwordFocusNode.hasFocus) {
        state = state.copyWith(passwordErrorText: null);
      }
    });

    confirmPasswordFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (confirmPasswordFocusNode.hasFocus) {
        state = state.copyWith(confirmPasswordErrorText: null);
      }
    });
  }

  //销毁资源
  void onDispose(ResetPasswordState initState) {
    final FocusNode codeFocusNode = initState.formData['code']!['focusNode'];
    final FocusNode passwordFocusNode = initState.formData['password']!['focusNode'];
    final FocusNode confirmPasswordFocusNode = initState.formData['confirm_password']!['focusNode'];
    codeFocusNode.dispose();
    passwordFocusNode.dispose();
    confirmPasswordFocusNode.dispose();

    countdownTimer?.cancel();

    Log.d("ForgotVerifyViewModel 销毁 onDispose");
  }
}
