import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:sigap/src/cores/services/location_service.dart';
import 'package:sigap/src/features/onboarding/data/dummy/onboarding_dummy.dart';
import 'package:sigap/src/utils/constants/app_routes.dart';
import 'package:sigap/src/utils/popups/circular_full_screen_loader.dart';

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

  // Storage for onboarding state
  final storage = GetStorage();

  // Location service
  final _locationService = Get.find<LocationService>();

  // Observable variables
  final RxInt currentIndex = 0.obs;
  final PageController pageController = PageController(initialPage: 0);
  // Tambahkan controller untuk PageView teks
  final PageController textPageController = PageController(initialPage: 0);
  final RxBool isLocationChecking = false.obs;

  // Animation controllers
  late AnimationController animationController;
  late Animation<double> fadeAnimation;
  late Animation<Offset> slideAnimation;

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

    // Initialize animation controllers
    animationController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: animationController, curve: Curves.easeIn),
    );

    slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.2),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(parent: animationController, curve: Curves.easeOut),
    );

    animationController.forward();
  }

  @override
  void onClose() {
    pageController.dispose();
    textPageController.dispose(); // dispose controller baru
    animationController.dispose();
    super.onClose();
  }

  // Method to handle page changes
  void onPageChanged(int index) {
    currentIndex.value = index;
    animationController.reset();
    animationController.forward();
    // Sinkronisasi textPageController dilakukan di widget, tidak perlu di sini
  }

  // Method to go to next page
  void nextPage() {
    if (currentIndex.value == contents.length - 1) {
      skipOnboarding();
    } else {
      pageController.nextPage(
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    }
  }

  // Method to skip to check location screen
  void skipToCheckLocation() {
    skipOnboarding();
  }

  // Method to navigate to check location screen
  void skipOnboarding() {
    // Mark onboarding as completed in storage
    storage.write('isFirstTime', false);
    Get.offAllNamed(AppRoutes.checkLocation);
  }

  // Method to check location validity and proceed with auth flow
  Future<void> getStarted() async {
    isLocationChecking.value = true;

    try {
      TCircularFullScreenLoader.openLoadingDialog(text: 'Checking location...');

      // Verify location is valid (in Jember and not mocked)
      final isLocationValid =
          await _locationService.isLocationValidForFeature();

      TCircularFullScreenLoader.stopLoading();

      storage.write('isFirstTime', false);

      if (isLocationValid) {
        // If location is valid, proceed to role selection

        Get.offAllNamed(AppRoutes.roleSelection);

        // Store isfirstTime to false in storage
      } else {
        // If location is invalid, show warning screen
        // TLoaders.errorSnackBar(
        //   title: 'Location Invalid',
        //   message:
        //       'Please enable location services or ensure you are in Jember area',
        // );
        
        Get.offAllNamed(AppRoutes.locationWarning);

      }
    } catch (e) {
      // If there's an error, show the location warning screen
      // TFullScreenLoader.stopLoading();
      Get.offAllNamed(AppRoutes.locationWarning);
    } finally {
      isLocationChecking.value = false;
      // TCircularFullScreenLoader.stopLoading();
    }
  }

  void goToSignIn() {
    storage.write('isFirstTime', false);

    Get.offAllNamed(AppRoutes.signIn);
  }
}
