import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:intl/intl.dart';
import 'package:get_storage/get_storage.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../../../routes/app_pages.dart'; // For flutter material imports


class HomeController extends GetxController {
  final DatabaseReference _database = FirebaseDatabase.instance.ref();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  final box = GetStorage();

  var username = "".obs;
  var internetStatus = false.obs;
  var koneksiAlat = false.obs;  // Menyimpan status koneksi alat
  var historyList = [].obs;
  var chartData = <Map<String, dynamic>>[].obs;

  @override
  void onInit() {
    super.onInit();
    initNotification();
    fetchUserData();
    checkInternetStatus();
    monitorKoneksiAlat();  // Mulai monitor koneksi alat
    fetchHistory();
    fetchChartData();
  }

  void initNotification() async {
    const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
    );
    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

 void fetchChartData() async {
    _firestore.collection('history_data')
      .orderBy('timestamp', descending: true)
      .limit(10)
      .snapshots()
      .listen((snapshot) {
        chartData.value = snapshot.docs.map((doc) {
          var data = doc.data();
          return {
            'nitrogen': (data['nitrogen'] ?? 0).toDouble(),
            'phosphorus': (data['phosphorus'] ?? 0).toDouble(),
            'potassium': (data['potassium'] ?? 0).toDouble(),
            'soil_moisture': (data['soil_moisture'] ?? 0).toDouble(),
            'timestamp': data['timestamp'] is Timestamp ? (data['timestamp'] as Timestamp).toDate() : null,
          };
        }).toList();
      });
  }

  void fetchUserData() async {
    User? user = _auth.currentUser;
    if (user != null) {
      DocumentSnapshot userDoc = await _firestore.collection('users').doc(user.uid).get();
      username.value = userDoc["name"] ?? "Pengguna";
    }
  }

  void checkInternetStatus() {
    Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      internetStatus.value = result.isNotEmpty && result.first != ConnectivityResult.none;
    });
  }

void monitorKoneksiAlat() {
  // Dengarkan perubahan nilai pada "sensor_data/update"
  _database.child('sensor_data/update').onValue.listen((event) {
    final updateValue = event.snapshot.value;

    if (updateValue != null) {
      // Cek apakah updateValue berbeda dengan sebelumnya
      String? lastValue = box.read('last_update_value');

      if (lastValue != updateValue) {
        // Jika berubah -> simpan nilai dan waktu saat ini
        box.write('last_update_value', updateValue.toString());
        box.write('last_update_time', DateTime.now().toString());

        if (!koneksiAlat.value) {
          print("Koneksi alat aktif.");
          koneksiAlat.value = true;
        }
      }
    }
  });

  // Timer pengecekan setiap 10 detik
  Future.doWhile(() async {
    await Future.delayed(Duration(seconds: 10));
    String? lastUpdateTimeStr = box.read('last_update_time');
    if (lastUpdateTimeStr != null) {
      DateTime lastUpdateTime = DateTime.parse(lastUpdateTimeStr);
      Duration diff = DateTime.now().difference(lastUpdateTime);

      if (diff.inMinutes >= 1) {
        if (koneksiAlat.value) {
          koneksiAlat.value = false;
          print("Koneksi alat terputus karena tidak ada update dalam 1 menit.");
          sendNotification("Koneksi Terputus", "Alat tidak mengirim data lebih dari 1 menit.");
          saveNotificationHistory("Koneksi Terputus", DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()));
        }
      }
    }
    return true;
  });
}

  void fetchHistory() async {
    _firestore.collection('history_data')
      .orderBy('timestamp', descending: true)
      .snapshots()
      .listen((snapshot) {
        historyList.value = snapshot.docs.map((doc) {
          final data = doc.data();
          data['title'] = 'Cek kondisi tanah'; // tetap tambahkan title jika ingin
          return data;
        }).toList();
      });
  }

  void sendNotification(String title, String body) async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'koneksi_channel',
      'Koneksi Alat',
      importance: Importance.max,
      priority: Priority.high,
      ticker: 'ticker',
    );
    const NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      0,
      title,
      body,
      platformChannelSpecifics,
      payload: 'koneksi_alat',
    );
  }
  void saveNotificationHistory(String title, String date) {
  List history = box.read('notification_history') ?? [];
  history.add({'judul': title, 'deskripsi': 'Alat tidak dapat terhubung. Harap cek koneksi.', 'waktu': date});
  box.write('notification_history', history);
}


  void keRiwayat() => Get.toNamed(Routes.HISTORY);
  void keNotifikasi() => Get.toNamed(Routes.NOTIFIKASI);
}
