import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

class PanicButtonController extends GetxController {
  static PanicButtonController get instance => Get.find();

  // Observable variables
  final RxBool isPanicActive = false.obs;
  final RxString locationString = "Indonesia · 125.161.172.145".obs;
  final RxInt elapsedSeconds = 0.obs;

  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    // Simulate fetching location
    _fetchLocation();
  }

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

  // Toggle panic mode on/off
  void togglePanicMode() {
    if (isPanicActive.value) {
      // If currently active, show confirmation dialog
      Get.dialog(
        AlertDialog(
          title: const Text('Cancel Emergency Alert?'),
          content: const Text(
            'Are you sure you want to cancel the emergency alert?',
          ),
          actions: [
            TextButton(onPressed: () => Get.back(), child: const Text('No')),
            TextButton(
              onPressed: () {
                Get.back();
                _deactivatePanicMode();
              },
              child: const Text('Yes'),
            ),
          ],
        ),
      );
    } else {
      // If not active, show confirmation to activate
      Get.dialog(
        AlertDialog(
          title: const Text('Confirm Emergency Alert'),
          content: const Text(
            'Are you sure you want to send an emergency alert?',
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () {
                Get.back();
                _activatePanicMode();
              },
              child: const Text(
                'Send Alert',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ],
        ),
      );
    }
  }

  void _activatePanicMode() {
    isPanicActive.value = true;
    elapsedSeconds.value = 0;
    _startTimer();

    // Show toast notification
    Get.snackbar(
      'Emergency Alert Active',
      'Help has been notified and is on the way',
      backgroundColor: Colors.red,
      colorText: Colors.white,
      icon: const Icon(Icons.warning_amber_rounded, color: Colors.white),
      snackPosition: SnackPosition.TOP,
      duration: const Duration(seconds: 3),
    );

    // TODO: Implement actual emergency services notification
  }

  void _deactivatePanicMode() {
    isPanicActive.value = false;
    _timer?.cancel();

    // Show toast notification
    Get.snackbar(
      'Emergency Alert Cancelled',
      'Your emergency alert has been cancelled',
      backgroundColor: Colors.green,
      colorText: Colors.white,
      icon: const Icon(Icons.check_circle, color: Colors.white),
      snackPosition: SnackPosition.TOP,
      duration: const Duration(seconds: 3),
    );

    // TODO: Implement actual emergency services cancellation
  }

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      elapsedSeconds.value++;
    });
  }

  void _fetchLocation() {
    // TODO: Implement actual location fetching
    // This is just a placeholder that simulates location fetch
    Future.delayed(const Duration(seconds: 2), () {
      locationString.value = "Jakarta, Indonesia · 125.161.172.145";
    });
  }

  // Format elapsed time as string
  String get elapsedTimeString {
    final seconds = elapsedSeconds.value;
    if (seconds < 60) {
      return '$seconds seconds ago';
    }
    final minutes = seconds ~/ 60;
    if (minutes < 60) {
      return '$minutes minutes ago';
    }
    final hours = minutes ~/ 60;
    return '$hours hours ago';
  }
}
