// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, sort_child_properties_last, deprecated_member_use
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class Dashboard extends StatefulWidget {
  const Dashboard({super.key});

  @override
  State<Dashboard> createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
   String currentDate = "";

  void _updateDate() {
    final now = DateTime.now();
    final formattedDate = DateFormat('EEEE, d MMMM yyyy','id_ID').format(now);
    setState(() {
      currentDate = formattedDate;
    });
  }
  final DatabaseReference _databaseReference =
      FirebaseDatabase().reference().child('minum').child('ph_value');
  final DatabaseReference _pakanreference =
      FirebaseDatabase().reference().child('pakan').child('distance');
      final DatabaseReference _minumDistance =
      FirebaseDatabase().reference().child('minum').child('distance');
  final DatabaseReference _turbiditastreference =
      FirebaseDatabase().reference().child('minum').child('turbidity_value');
  final DatabaseReference _pagiReference =
      FirebaseDatabase().reference().child('pakan').child('pakan_pagi');
  final DatabaseReference _soreReference =
      FirebaseDatabase().reference().child('pakan').child('pakan_sore');

  String _pHValue = "";
  String _pakanValue = "";
  String _tinggiMinum = "";
  String _turbiditasValue = "";
  String _pakanPagi = "";
  String _pakanSore = "";

  @override
  void initState() {
    super.initState();
    fetchData();
    _updateDate();
  }

  Future fetchData() async {
  try {
    DatabaseEvent eventPH = await _databaseReference.once();
    DatabaseEvent eventPakan = await _pakanreference.once();
    DatabaseEvent eventMinum = await _minumDistance.once();
    DatabaseEvent eventTurbiditas = await _turbiditastreference.once();
    DatabaseEvent eventPagi = await _pagiReference.once();
    DatabaseEvent eventSore = await _soreReference.once();

    if (eventPH.snapshot.value != null &&
        eventPakan.snapshot.value != null &&
        eventMinum.snapshot.value != null &&
        eventTurbiditas.snapshot.value != null &&
        eventPagi.snapshot.value != null &&
        eventSore.snapshot.value != null 
        ) {
      setState(() {
        _pHValue = eventPH.snapshot.value.toString();
        _pakanValue = eventPakan.snapshot.value.toString();
        _tinggiMinum = eventMinum.snapshot.value.toString();
        _turbiditasValue = eventTurbiditas.snapshot.value.toString();
        _pakanPagi = eventPagi.snapshot.value.toString();
        _pakanSore = eventSore.snapshot.value.toString();
      });

      return eventPH.snapshot.value;
    }
  } catch (e) {
    print("Error fetching data: $e");
    return e;
  }
}



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
      future: fetchData(),
      builder: (context,snapshot){
        if(snapshot.hasData){
          return ListView(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 30, right: 30, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Container(
                //   child: Text("Ph value: $_pHValue"),
                // ),
                // Divider(),
                // Container(
                //   child: Text("Jarak pakan: $_pakanValue"),
                // ),
                // Divider(),
                // Container(
                //   child: Text("Turbit value: $_turbiditasValue"),
                // ),
                
                const Text(
                  "Hari ini",
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                Text(
                  currentDate,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20),
                  padding: EdgeInsets.all(10),
                  width: MediaQuery.of(context).size.width,
                  height: 215,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0, 3),
                        blurRadius: 10,
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Image.asset("images/icon-pakan.png"),
                          Padding(
                            padding: const EdgeInsets.only(left: 10),
                            child: Text(
                              "Pakan Ayam",
                              style: TextStyle(
                                fontSize: 15,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(),
                      Container(
                        margin: EdgeInsets.only(top: 10, bottom: 5,left: 8,right: 8),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: Text("Makan Pagi pada jam : $_pakanPagi"),
                        decoration: BoxDecoration(
                          color: Color(0xff9DC08B).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 5,left: 8,right: 8),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: Text("Makan sore pada jam : $_pakanSore"),
                        decoration: BoxDecoration(
                          color: Color(0xffFFB015).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 4,left: 8,right: 8),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: 
                        (double.parse(_pakanValue) >= 25) ?
                        Text("Pakan habis! Segera isi ulang pakan!") :Text("Pakan penuh"),
                        decoration: BoxDecoration(
                          color: (double.parse(_pakanValue) >= 25) ? Color.fromARGB(255, 240, 52, 38).withOpacity(0.8):Color(0xff08F842).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20),
                  padding: EdgeInsets.all(10),
                  width: MediaQuery.of(context).size.width,
                  height: 210,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0, 3),
                        blurRadius: 10,
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Image.asset("images/icon-ph.png"),
                          Padding(
                            padding: const EdgeInsets.only(left: 10),
                            child: Text(
                              "Air minum",
                              style: TextStyle(
                                fontSize: 15,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(),
                      Container(
                        margin: EdgeInsets.only(bottom: 5,left: 8,right: 8, top: 10),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: 
                        (double.parse(_tinggiMinum) >= 32) ?
                        Text("Air Hampir Habis") :Text("Air penuh"),
                        decoration: BoxDecoration(
                          color: (double.parse(_tinggiMinum) >= 32) ? Color.fromARGB(255, 240, 52, 38).withOpacity(0.8):Color(0xff97DEFF).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 5,left: 8,right: 8),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: 
                        (double.parse(_pHValue) >= 8.5) ?
                        Text("Kadar PH Tinggi") : (double.parse(_pHValue) < 5.5) ?Text("Kadar PH Rendah") :Text("Kadar PH Normal"),
                        decoration: BoxDecoration(
                          color: (double.parse(_pHValue) >= 8.5) ? Color.fromARGB(255, 240, 52, 38).withOpacity(0.8):(double.parse(_pHValue) < 5.5) ?Color(0xff97DEFF).withOpacity(0.8):Color(0xff08F842).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 2,left: 8,right: 8),
                        padding: EdgeInsets.all(10),
                        width: MediaQuery.of(context).size.width,
                        child: 
                          (double.parse(_turbiditasValue) >= 2000) ?
                        Text("Air Keruh") : Text("Air Bersih"),
                        decoration: BoxDecoration(
                          color: (double.parse(_turbiditasValue) >= 2000) ? Color.fromARGB(255, 228, 126, 118).withOpacity(0.8):Color(0xff08F842).withOpacity(0.8),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 159.5),
                  child: Center(
                      child: Text(
                    "Copyright @2023 Team Dev MBKM All Right Reserved",
                    style: TextStyle(fontSize: 11),
                  )),
                ),
                
              ],
            ),
          ),
        ],
      );
        }
        if(snapshot.hasError){
          Center(
            child: Text("Terjadi kesalahan"),
          );
        }
        return Center(child: CircularProgressIndicator(color: Colors.amber,));
      }),
    );
  }
}
