import 'dart:async';

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_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:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../auth_login/auth_login_page.dart';
import 'forgot_verify_state.dart';

part 'forgot_verify_view_model.g.dart';

@riverpod
class ForgotVerifyViewModel extends _$ForgotVerifyViewModel with DioCancelableMixin {
  late final AuthRepository _authRepository;

  @override
  ForgotVerifyState build() {
    _authRepository = ref.read(authRepositoryProvider);

    final state = ForgotVerifyState();
    initListener(state);

    registerCancellation(callback: () {
      onDispose(state);
    });

    return state;
  }

  //提交重置密码的校验
  void submitVerify(String? phone) async {
    state = state.copyWith(codeErrorText: null, passwordErrorText: null, confirmPasswordErrorText: null);

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

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

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

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

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

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

    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.forgotPassword(
      smsCode: code,
      countryCode: Utils.getMobileCode(phone ?? ""),
      phone: Utils.getRealMobile(phone ?? ""),
      password: password,
      confirmPassword: confirmPassword,
      cancelToken: cancelToken,
    );

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

  //去登录页面
  void gotoLoginPage() {
    AuthLoginPage.startInstance();
  }

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

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

  // 验证弹窗
  showVerifyCodedDialog(String? phone) {
    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: Utils.getMobileCode(phone ?? ""),
      phone: Utils.getRealMobile(phone ?? ""),
      captchaKey: key,
      captchaValue: code,
      cancelToken: cancelToken,
    );

    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(ForgotVerifyState initState) {
    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(ForgotVerifyState 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");
  }
}
