import 'dart:async';

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/presentasion/pages/role-selection/role_signup_pageview.dart';
import 'package:sigap/src/utils/constants/image_strings.dart';

class CheckLocationController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final VoidCallback? onSuccess;
  final LocationService _locationService = LocationService.instance;

  final storage = GetStorage();

  // Reactive variables
  final RxInt currentPage = 0.obs;
  final RxBool isLoading = false.obs;
  final RxBool isLocationValid = false.obs;
  final RxString errorMessage = ''.obs;
  final RxBool showUIElements = true.obs;
  final RxBool bottomSheetShown = false.obs;

  // Controllers
  late PageController pageController;
  late AnimationController animController;
  late Animation<double> scaleAnimation;
  late Timer autoSlideTimer;

  // Slide data
  final List<Map<String, dynamic>> slides = [
    {
      'image': TImages.womanHuggingEarth,
      'title': 'Location Verification',
      'subtitle':
          'We need to verify your location as this app is specifically designed for the Jember region',
    },
    {
      'image': TImages.communication,
      'title': 'Region-Specific Services',
      'subtitle':
          'Our emergency services and features are only available within Jember boundaries',
    },
    {
      'image': TImages.callingHelp,
      'title': 'Your Safety Matters',
      'subtitle':
          'Location validation ensures you receive appropriate assistance when needed',
    },
  ];

  CheckLocationController({this.onSuccess});

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

    // Initialize controllers
    pageController = PageController(viewportFraction: 0.8);

    // Setup animation controllers
    animController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 60.0,
    ).animate(CurvedAnimation(parent: animController, curve: Curves.easeInOut));

    // Add listeners
    animController.addStatusListener(_handleAnimationStatusChanged);
    scaleAnimation.addListener(_handleScaleAnimationChanged);

    // Start auto slide timer
    autoSlideTimer = Timer.periodic(Duration(seconds: 3), _handleAutoSlide);

    // Show bottom sheet after a delay
    Future.delayed(Duration(seconds: 1), showBottomSheet);
  }

  @override
  void onClose() {
    autoSlideTimer.cancel();
    pageController.dispose();
    animController.dispose();
    super.onClose();
  }

  // Navigate to communication slide (index 1) before zooming
  void _navigateToCommunicationSlide() {
    if (currentPage.value != 1) {
      pageController.animateToPage(
        1, // Index for TImages.communication
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _handleAnimationStatusChanged(AnimationStatus status) {
    if (status == AnimationStatus.completed) {
      // Instead of calling onSuccess callback directly, navigate to RoleSelectionScreen
      Get.off(
        () => RoleSignupPageView(),
        transition: Transition.fadeIn,
        duration: const Duration(milliseconds: 300),
      );

      // Call the onSuccess callback after navigation if provided
      if (onSuccess != null) {
        Timer(Duration(milliseconds: 100), onSuccess!);
      }
    }
  }

  void _handleScaleAnimationChanged() {
    if (scaleAnimation.value > 1.2) {
      showUIElements.value = false;
    }
  }

  void _handleAutoSlide(Timer timer) {
    if (pageController.hasClients) {
      final nextPage = (currentPage.value + 1) % slides.length;
      pageController.animateToPage(
        nextPage,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    }
  }

  void onPageChanged(int index) {
    currentPage.value = index;
  }

  Future<void> checkLocation() async {
    isLoading.value = true;
    try {
      final result = await _locationService.validateLocationForPanicButton();

      if (result['valid']) {
        isLoading.value = false;
        isLocationValid.value = true;

        // Navigate to communication slide before zooming
        _navigateToCommunicationSlide();

        storage.write('isFirstTime', false);

        // Give time to see the success message before animating
        await Future.delayed(Duration(milliseconds: 800));
        animController
            .forward(); // Start zoom-in animation which will trigger the navigation
      } else {
        isLoading.value = false;
        isLocationValid.value = false;
        errorMessage.value = result['message'] ?? 'Location is invalid';

        // Force page to show error slide
        pageController.jumpToPage(slides.length - 1);
      }
    } catch (e) {
      isLoading.value = false;
      isLocationValid.value = false;
      errorMessage.value = 'Failed to check location. Please try again.';
    }
  }

  void handleButtonPress() {
    if (isLocationValid.value) {
      // Navigate to communication slide before zooming
      _navigateToCommunicationSlide();

      // Give a brief moment for the page transition to complete
      Future.delayed(Duration(milliseconds: 300), () {
        animController
            .forward(); // This will trigger the navigation when animation completes
      });
    } else {
      isLoading.value = true;
      checkLocation();
    }
  }

  void showBottomSheet() {
    bottomSheetShown.value = true;
    // Actual bottom sheet will be shown from the UI
  }
}
