import 'dart:async';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/base/base_response_model.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/screen/create_pass/create_pass_screen.dart';
import 'package:mypoint_flutter_app/screen/login/login_screen.dart';
import '../create_pass/signup_create_password_repository.dart';
import 'model/otp_verify_response_model.dart';

abstract class IOtpRepository {
  Future<void> sendOtp();
  Future<BaseResponseModel<OTPVerifyResponseModel>> verifyOtp(String otpCode);
  Future<int?> resendOtp();
  late String phoneNumber;
  late int otpTtl;
}

class OtpViewModel extends GetxController {
  final IOtpRepository repository;
  var otpCode = "".obs;
  var errorMessage = "".obs;
  var currentCountdown = 0.obs;
  int _maxCountdown = Constants.otpTtl;
  Timer? _timer;

  OtpViewModel(this.repository);

  @override
  void onInit() {
    super.onInit();
    _maxCountdown = repository.otpTtl;
    sendOtp();
    startCountdown();
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  Future<void> sendOtp() async {
    try {
      await repository.sendOtp();
      startCountdown();
    } catch (e) {
      errorMessage.value = "Gửi OTP thất bại. Vui lòng thử lại.";
    }
  }

  void startCountdown() {
    currentCountdown.value = _maxCountdown;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (currentCountdown.value <= 0) {
        timer.cancel();
      } else {
        currentCountdown.value--;
      }
    });
  }

  String get countdownText {
    final m = currentCountdown.value ~/ 60;
    final s = currentCountdown.value % 60;
    final sStr = s < 10 ? "0$s" : "$s";
    return "$m:$sStr";
  }

  void onOtpChanged(String value) {
    otpCode.value = value;
    errorMessage.value = "";
  }

  Future<void> onSubmitOtp() async {
    if (otpCode.value.length < 6) {
      errorMessage.value = "Nhập đủ 6 ký tự";
      return;
    }
    try {
      final response = await repository.verifyOtp(otpCode.value);
      if (response.isSuccess) {
        errorMessage.value = "";
        if (response.data?.claim?.action == "signup") {
          Get.off(() => CreatePasswordScreen(repository: SignUpCreatePasswordRepository(repository.phoneNumber)));
          return;
        }
        if (response.data?.claim?.action == "login") {
          Get.off(() => LoginScreen(phoneNumber: repository.phoneNumber));
          return;
        }
      } else {
        errorMessage.value = response.errorMessage ?? "";
      }
    } catch (e) {
      // Bắt lỗi do repository throw
      errorMessage.value = "Xác thực thất bại: $e";
    }
  }

  Future<int?> onResendOtp() async {
    if (currentCountdown.value > 0) return null;
    try {
      final response = await repository.resendOtp();
      _maxCountdown = response ?? Constants.otpTtl;
      startCountdown();
    } catch (e) {
      errorMessage.value = "Gửi lại OTP thất bại. Thử lại.";
    }
  }
}