import 'dart:async';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/shared/widgets/base_view/base_response_model.dart';
import 'package:mypoint_flutter_app/app/config/constants.dart';

abstract class IOtpRepository {
  Future<void> sendOtp();
  Future<BaseResponseModel<EmptyCodable>> 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 {
  }

  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 = "";
      } else {
        errorMessage.value =
            response.errorMessage ??
            response.message ??
            Constants.commonError;
      }
    } catch (e) {
      // Bắt lỗi do repository throw
      errorMessage.value = "Xác thực thất bại: $e";
    }
  }

  Future<void> onResendOtp() async {
    if (currentCountdown.value > 0) return;
    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.";
    }
  }
}