import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/repositories/authentication_repository.dart';
import 'package:sigap/src/utils/constants/app_routes.dart';
import 'package:sigap/src/utils/popups/loaders.dart';

class EmailVerificationController extends GetxController {
  // Singleton instance
  static EmailVerificationController get instance => Get.find();

  // OTP text controllers
  final List<TextEditingController> otpControllers = List.generate(
    6,
    (_) => TextEditingController(),
  );

  // Focus nodes for OTP fields
  final List<FocusNode> focusNodes = List.generate(6, (_) => FocusNode());

  // Observable variables
  final RxBool isLoading = false.obs;
  final RxBool isVerified = false.obs;
  final RxBool isResendEnabled = false.obs;
  final RxInt resendCountdown = 60.obs;
  final RxString verificationError = ''.obs;

  // Timer for resend countdown
  Timer? _countdownTimer;

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

  @override
  void onClose() {
    _countdownTimer?.cancel();
    for (var controller in otpControllers) {
      controller.dispose();
    }
    for (var node in focusNodes) {
      node.dispose();
    }
    super.onClose();
  }

  // Start the resend timer
  void startResendTimer() {
    resendCountdown.value = 60;
    isResendEnabled.value = false;

    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (resendCountdown.value > 0) {
        resendCountdown.value--;
      } else {
        isResendEnabled.value = true;
        timer.cancel();
      }
    });
  }

  // Handle OTP input change
  void onOtpChanged(String value, int index) {
    if (value.length == 1) {
      // Move to next field
      if (index < otpControllers.length - 1) {
        focusNodes[index + 1].requestFocus();
      } else {
        // Last field filled, hide keyboard
        focusNodes[index].unfocus();
        // Verify OTP automatically when all fields are filled
        verifyOtp();
      }
    }
  }

  // Get the complete OTP
  String getOtp() {
    return otpControllers.map((controller) => controller.text).join();
  }

  // Verify OTP
  Future<void> verifyOtp() async {
    final otp = getOtp();

    // Check if OTP is complete
    if (otp.length != otpControllers.length) {
      verificationError.value = 'Please enter the complete verification code';
      return;
    }

    try {
      isLoading.value = true;
      verificationError.value = '';

      final authuser = await AuthenticationRepository.instance.verifyOtp(otp);

      if (authuser.session == null || authuser.user == null) {
        verificationError.value = 'Invalid OTP. Please try again.';
        return;
      }

      isVerified.value = true;

      TLoaders.successSnackBar(
        title: 'Verification Successful',
        message: 'Your email has been verified successfully.',
      );

      Get.offNamed(AppRoutes.roleSelection);
    } catch (e) {
      verificationError.value = 'Verification failed: ${e.toString()}';
    } finally {
      isLoading.value = false;
    }
  }

  // Resend verification code
  Future<void> resendCode(String email) async {
    if (!isResendEnabled.value) return;

    try {
      isLoading.value = true;

      await AuthenticationRepository.instance.resendEmailVerification(email);

      // Reset the timer
      startResendTimer();

      // Clear fields
      for (var controller in otpControllers) {
        controller.clear();
      }

      // Focus on first field
      focusNodes[0].requestFocus();

      // Show success message
      TLoaders.successSnackBar(
        title: 'Code Resent',
        message: 'A new verification code has been sent to your email.',
      );
    } catch (e) {
      verificationError.value = 'Resend failed: ${e.toString()}';

      TLoaders.errorSnackBar(
        title: 'Resend Failed',
        message: 'Failed to resend the verification code. Please try again.',
      );
    } finally {
      isLoading.value = false;
    }
  }

  // Go back to sign in
  void goToSignIn() {
    Get.offAllNamed(AppRoutes.signIn);
  }
}
