import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:geolocator/geolocator.dart';

class ModeController extends GetxController {
  final databaseReference = FirebaseDatabase.instance.ref();
  final firestore = FirebaseFirestore.instance;

  RxDouble nitrogen = 0.0.obs;
  RxDouble phosphorus = 0.0.obs;
  RxDouble potassium = 0.0.obs;
  RxDouble soilMoisture = 0.0.obs;

  RxString mode = 'Auto'.obs; // Tambahan: default mode auto
  RxList<String> kebunList = <String>[].obs;
  RxString selectedKebun = ''.obs;

  TextEditingController farmController = TextEditingController();
  TextEditingController locationController = TextEditingController();

  TextEditingController manualNitrogenController = TextEditingController();
  TextEditingController manualPhosphorusController = TextEditingController();
  TextEditingController manualPotassiumController = TextEditingController();
  TextEditingController manualSoilMoistureController = TextEditingController();

  Rx<Position?> currentPosition = Rx<Position?>(null);

  DateTime? _lastAutoSave;

  @override
  void onInit() {
    super.onInit();
    fetchSensorData();
    fetchKebunList();
    getCurrentLocation();
    updateSelectedKebunFromLastHistory();
  }

  void fetchSensorData() {
    databaseReference.child('sensor_data').onValue.listen((event) async {
      if (mode.value == 'Auto') {
        final data = event.snapshot.value as Map<dynamic, dynamic>;
        nitrogen.value = double.tryParse(data['nitrogen'].toString()) ?? 0.0;
        phosphorus.value = double.tryParse(data['phosphorus'].toString()) ?? 0.0;
        potassium.value = double.tryParse(data['potassium'].toString()) ?? 0.0;
        soilMoisture.value = double.tryParse(data['soil_moisture'].toString()) ?? 0.0;
        // Hapus auto save, hanya update nilai sensor saja
      }
    });
  }

  void fetchKebunList() async {
    final snapshot = await firestore.collection('kebun').get();
    kebunList.value = snapshot.docs.map((doc) => doc['nama_kebun'].toString()).toList();
  }

  void refreshSensorData() {
    fetchSensorData();
  }

  void setMode(String newMode) {
    mode.value = newMode;
    if (newMode == 'Auto') {
      fetchSensorData();
      updateSelectedKebunFromLastHistory();
    }
  }

  Future<void> saveModeData() async {
    String farmName = mode.value == 'Auto'
        ? selectedKebun.value
        : farmController.text;

    String locationString = mode.value == 'Auto' && currentPosition.value != null
        ? '${currentPosition.value!.latitude}, ${currentPosition.value!.longitude}'
        : locationController.text;

    if (farmName.isEmpty || locationString.isEmpty) {
      Get.snackbar('Error', 'Semua field harus diisi!',
          snackPosition: SnackPosition.BOTTOM);
      return;
    }

    double nitrogenValue = nitrogen.value;
    double phosphorusValue = phosphorus.value;
    double potassiumValue = potassium.value;
    double soilMoistureValue = soilMoisture.value;

    // Kalau mode Manual, ambil dari input manual
    if (mode.value == 'Manual') {
      nitrogenValue = double.tryParse(manualNitrogenController.text) ?? 0.0;
      phosphorusValue = double.tryParse(manualPhosphorusController.text) ?? 0.0;
      potassiumValue = double.tryParse(manualPotassiumController.text) ?? 0.0;
      soilMoistureValue = double.tryParse(manualSoilMoistureController.text) ?? 0.0;
    }

    // Ambil posisi
    final pos = currentPosition.value;

    await firestore.collection('history_data').add({
      'farm': farmName,
      'location': locationString,
      'latitude': pos?.latitude,
      'longitude': pos?.longitude,
      'nitrogen': nitrogenValue,
      'phosphorus': phosphorusValue,
      'potassium': potassiumValue,
      'soilMoisture': soilMoistureValue,
      'timestamp': FieldValue.serverTimestamp(),
    });

    Get.snackbar('Berhasil', 'Data berhasil disimpan!',
        snackPosition: SnackPosition.BOTTOM);

    // Reset form jika perlu
    farmController.clear();
    locationController.clear();
    manualNitrogenController.clear();
    manualPhosphorusController.clear();
    manualPotassiumController.clear();
    manualSoilMoistureController.clear();
  }

  Future<void> getCurrentLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Get.snackbar('Lokasi tidak aktif', 'Aktifkan layanan lokasi di perangkat Anda.');
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Get.snackbar('Izin lokasi ditolak', 'Aplikasi membutuhkan izin lokasi.');
        return;
      }
    }
    if (permission == LocationPermission.deniedForever) {
      Get.snackbar('Izin lokasi ditolak permanen', 'Buka pengaturan untuk mengaktifkan izin lokasi.');
      return;
    }

    final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    currentPosition.value = position;
    locationController.text = '${position.latitude}, ${position.longitude}';
  }

  Future<void> updateSelectedKebunFromLastHistory() async {
    final snapshot = await firestore
        .collection('history_data')
        .orderBy('timestamp', descending: true)
        .limit(1)
        .get();
    if (snapshot.docs.isNotEmpty) {
      final data = snapshot.docs.first.data();
      if (data['farm'] != null) {
        selectedKebun.value = data['farm'];
        farmController.text = data['farm'];
      }
      if (data['latitude'] != null && data['longitude'] != null) {
        locationController.text = '${data['latitude']}, ${data['longitude']}';
        currentPosition.value = Position(
          latitude: (data['latitude'] as num).toDouble(),
          longitude: (data['longitude'] as num).toDouble(),
          timestamp: DateTime.now(),
          accuracy: 0,
          altitude: 0,
          heading: 0,
          speed: 0,
          speedAccuracy: 0,
          altitudeAccuracy: 0,
          headingAccuracy: 0,
        );
      }
    }
  }
}
