import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:uuid/uuid.dart';
import 'dart:convert'; // Tambahkan ini untuk parsing JSON
import 'mqtt_manager.dart';

class MonitoringSensorPage extends StatefulWidget {
  final String title;

  const MonitoringSensorPage({Key? key, required this.title}) : super(key: key);

  @override
  _MonitoringSensorPageState createState() => _MonitoringSensorPageState();
}

class _MonitoringSensorPageState extends State<MonitoringSensorPage> {
  String _kelembabanTanah = '';
  String _suhuTanah = '';
  String _cahaya = '';
  String _statusBaterai = '';
  String _kelembaban = '';
  late MQTTManager _mqttManager;
  final DatabaseReference _database = FirebaseDatabase.instance.reference();
  DateTime? _lastSavedTime;

  @override
  void initState() {
    super.initState();
    final uuid = Uuid();
    final clientId = 'flutter_client_${uuid.v4()}'; // Unique Client ID
    _mqttManager = MQTTManager(
      serverUri: '192.168.43.27', // Server URI
      clientId: clientId,
      onDataReceived: _onDataReceived,
    );
    _mqttManager.connect();
  }

  @override
  void dispose() {
    _mqttManager.disconnect();
    super.dispose();
  }

  void _onDataReceived(String soil, String humidity, String temperature,
      String intensity, String batLevel) {
    if (!mounted) return; // Check if the widget is still mounted

    setState(() {
      // Parsing nilai dan mengatur state
      _kelembabanTanah = soil;
      _kelembaban = humidity;
      _suhuTanah = temperature;
      _cahaya = intensity;
      _statusBaterai = batLevel;
    });

    final currentTime = DateTime.now();
    if (_lastSavedTime == null ||
        currentTime.difference(_lastSavedTime!).inMinutes >= 5) {
      _lastSavedTime = currentTime;
      _saveToDatabase(soil, humidity, temperature, intensity, batLevel);
    }
  }

  void _saveToDatabase(String soil, String humidity, String temperature,
      String intensity, String batLevel) {
    final sensorData = {
      'soil': soil,
      'humidity': humidity,
      'temperature': temperature,
      'intensity': intensity,
      'battery': batLevel,
      'timestamp': DateTime.now().toIso8601String(),
    };
    _database.child('sensor_data').push().set(sensorData);
  }

  void _onMessage(String message) {
    try {
      final data = jsonDecode(message);
      final soil = data['soil'].toString();
      final humidity = data['humidity'].toString();
      final temperature = data['temperature'].toString();
      final intensity = data['intensity'].toString();
      final batLevel = data['batlevel'].toString();

      _onDataReceived(soil, humidity, temperature, intensity, batLevel);
    } catch (e) {
      print('Error parsing JSON: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pushReplacementNamed(context, '/home');
          },
        ),
        backgroundColor: Colors.brown,
        title: Text(
          widget.title,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontFamily: 'Quicksand',
          ),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildSensorContainer(
                  color: Colors.blue,
                  icon: Icons.opacity,
                  label: 'Humidity: $_kelembaban %',
                ),
                SizedBox(width: 20),
                _buildSensorContainer(
                  color: Colors.green,
                  icon: Icons.thermostat,
                  label: 'Soil: $_kelembabanTanah Rh',
                ),
              ],
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildSensorContainer(
                  color: Colors.orange,
                  icon: Icons.wb_sunny,
                  label: 'Cahaya: $_cahaya lux',
                ),
                SizedBox(width: 20),
                _buildSensorContainer(
                  color: Colors.purple,
                  icon: Icons.battery_full,
                  label: 'Baterai: $_statusBaterai V',
                ),
              ],
            ),
            SizedBox(height: 20),
            _buildSensorContainer(
              color: Colors.red,
              icon: Icons.water_damage,
              label: 'Temperature: $_suhuTanah °C',
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSensorContainer({
    required Color color,
    required IconData icon,
    required String label,
  }) {
    return Container(
      width: 150,
      height: 150,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black26,
            blurRadius: 10,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 50, color: Colors.white),
          Text(
            label,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'Quicksand',
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
