import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:get/get.dart';

class DashboardController extends GetxController {
  var suhu = 50.0.obs; // Suhu yang dapat di-observe
  var waktu = 60.obs; // Waktu yang dapat di-observe
  var waktuTersisa = 60.obs; // Waktu tersisa dalam detik
  var isTimerRunning = false.obs; // Menandakan apakah timer sedang berjalan
  var statusPengeringan = "Tidak Ada Pengeringan".obs; // Status pengeringan
  var suhuTerkini = 0.0.obs;
  var isOnline = false.obs;

  late Timer _timer;

  // Riwayat pengeringan (format: tanggal & durasi)
  var riwayatList = <Map<String, dynamic>>[].obs;

  // Fungsi perhitungan otomatis waktu dari suhu (dalam menit)
  int hitungWaktuDariSuhu(double suhuInput) {
    if (suhuInput < 35) suhuInput = 35;
    if (suhuInput > 100) suhuInput = 100;

    Map<int, int> suhuToMenit = {
      35: 540,
      40: 420,
      45: 350,
      50: 294,
      55: 252,
      60: 216,
      65: 192,
      70: 168,
      75: 150,
      80: 138,
      85: 126,
      90: 120,
      95: 114,
      100: 108,
    };

    int rounded = suhuInput.round();
    if (suhuToMenit.containsKey(rounded)) {
      return suhuToMenit[rounded]!;
    }

    int lower = suhuInput.floor();
    int upper = suhuInput.ceil();

    int lowerMenit = suhuToMenit[lower] ?? 540;
    int upperMenit = suhuToMenit[upper] ?? 108;

    // Cegah pembagian 0
    if (upper == lower) {
      return lowerMenit;
    }

    double interpolasi =
        lowerMenit +
        (suhuInput - lower) * (upperMenit - lowerMenit) / (upper - lower);

    // Cegah NaN / Infinity
    if (interpolasi.isNaN || interpolasi.isInfinite) {
      return lowerMenit;
    }

    return interpolasi.round();
  }

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

  void stopTimer({bool dibatalkan = true}) {
    if (isTimerRunning.value) {
      _timer.cancel();
      isTimerRunning.value = false;

      // Set status terlebih dahulu, lalu simpan ke riwayat
      statusPengeringan.value =
          dibatalkan ? "Dibatalkan" : "Pengeringan Selesai";

      waktuTersisa.value = 0;
    }
  }

  void startCountdown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (waktuTersisa.value > 0) {
        waktuTersisa.value--;
      } else {
        _timer.cancel();
        isTimerRunning.value = false;

        statusPengeringan.value = "Pengeringan Selesai";
      }
    });
  }

  String getDurasiFormatted(int menit) {
    final jam = menit ~/ 60;
    final sisaMenit = menit % 60;
    return '${jam > 0 ? '$jam jam ' : ''}$sisaMenit menit';
  }

  void startTimer() {
    if (!isTimerRunning.value && waktuTersisa.value > 0) {
      isTimerRunning.value = true;
      statusPengeringan.value = "Pengeringan Sedang Berjalan";
      startCountdown();
    }
  }

  void saveSettings(double newSuhu, int newWaktu) {
    suhu.value = newSuhu;
    waktu.value = newWaktu;
    waktuTersisa.value = newWaktu * 60;
    isTimerRunning.value = true;
    statusPengeringan.value = "Pengeringan Sedang Berjalan";
    startCountdown();
  }

  // Fungsi untuk menambahkan ke riwayat
  Future<void> riwayatFirebase() async {
    final ref = FirebaseDatabase.instance.ref("Riwayat");
    final snapshot = await ref.get();

    if (snapshot.exists) {
      final data = Map<String, dynamic>.from(snapshot.value as Map);
      final listRiwayat =
          data.values
              .map<Map<String, dynamic>>((e) => Map<String, dynamic>.from(e))
              .toList()
              .reversed
              .toList(); // agar terbaru di atas

      riwayatList.assignAll(listRiwayat);
    } else {
      riwayatList.clear();
    }
  }

  @override
  void onInit() {
    super.onInit();
    dataTemperature();
    listenToStatusOnline();
  }

  void dataTemperature() {
    final ref = FirebaseDatabase.instance.ref("Thermocouple/Temperature");

    ref.onValue.listen((DatabaseEvent event) {
      final data = event.snapshot.value;
      if (data != null) {
        suhuTerkini.value = double.tryParse(data.toString()) ?? 0.0;
      }
    });
  }

  void listenToStatusOnline() {
    final ref = FirebaseDatabase.instance.ref("status_online");

    ref.onValue.listen((event) {
      final data = event.snapshot.value;
      isOnline.value = data == true;
    });
  }
}
