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

class RangeControlPage extends StatefulWidget {
  @override
  _RangeControlPageState createState() => _RangeControlPageState();
}

class _RangeControlPageState extends State<RangeControlPage> {
  final DatabaseReference _dbRef = FirebaseDatabase.instance.ref("ranges");
  int selectedWeek = 1;
  Map<String, dynamic> ranges = {};

  @override
  void initState() {
    super.initState();
    _fetchRangesFromFirebase();
  }

  void _fetchRangesFromFirebase() {
    _dbRef.onValue.listen((event) {
      final data = event.snapshot.value;
      if (data != null) {
        setState(() {
          ranges = Map<String, dynamic>.from(data as Map);
        });
      }
    });
  }

  Future<void> _updateRange(String type, String value, double newValue) async {
    String path = "week$selectedWeek/$type/$value";
    await _dbRef.child(path).set(newValue);
  }

  Widget _buildRangeSlider(String type, String value, double min, double max) {
    double currentValue = ranges['week$selectedWeek']?[type]?[value]?.toDouble() ?? min;
    
    return Column(
      children: [
        Text(
          "${type == 'temperature' ? 'Suhu' : 'Kelembapan'} ${value == 'min' ? 'Minimum' : value == 'max' ? 'Maksimum' : 'Target'}",
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        Slider(
          value: currentValue,
          min: min,
          max: max,
          divisions: (max - min).toInt() * 2,
          label: currentValue.toStringAsFixed(1),
          onChanged: (newValue) {
            _updateRange(type, value, newValue);
          },
        ),
        Text(
          "${currentValue.toStringAsFixed(1)}${type == 'temperature' ? '°C' : '%'}",
          style: TextStyle(fontSize: 18),
        ),
        SizedBox(height: 20),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFFA82429),
        title: Text(
          "Kontrol Rentang",
          style: TextStyle(color: Colors.white),
        ),
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            // Pemilih minggu
            DropdownButtonFormField<int>(
              value: selectedWeek,
              decoration: InputDecoration(
                labelText: "Pilih Minggu",
                border: OutlineInputBorder(),
              ),
              items: [1, 2, 3, 4].map((week) {
                return DropdownMenuItem(
                  value: week,
                  child: Text("Minggu $week"),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  selectedWeek = value!;
                });
              },
            ),
            SizedBox(height: 30),
            
            // Kontrol suhu
            Text(
              "Rentang Suhu",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            _buildRangeSlider("temperature", "min", 20, 40),
            _buildRangeSlider("temperature", "target", 20, 40),
            _buildRangeSlider("temperature", "max", 20, 40),
            
            Divider(height: 40),
            
            // Kontrol kelembapan
            Text(
              "Rentang Kelembapan",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            _buildRangeSlider("humidity", "min", 30, 80),
            _buildRangeSlider("humidity", "target", 30, 80),
            _buildRangeSlider("humidity", "max", 30, 80),
          ],
        ),
      ),
    );
  }
} 