import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';


class jadwal extends StatefulWidget {
  const jadwal({Key? key}) : super(key: key);
  @override
  State<jadwal> createState() => _jadwalState();
}

class _jadwalState extends State<jadwal> {
  
  String currentDate = "";
  void _updateDate() {
    final now = DateTime.now();
    final formattedDate = DateFormat('EEEE, d MMMM yyyy', 'id_ID').format(now);
    setState(() {
      currentDate = formattedDate;
    });
  }

  Future<void> savePakanToFirebase(String pakanPagi, String pakanSore) async {
    DatabaseReference databaseReference =
        FirebaseDatabase.instance.reference().child('pakan');
    await databaseReference.update({
      'pakan_pagi': pakanPagi,
      'pakan_sore': pakanSore,
    });
    
  }

  TimeOfDay selectedMorningTime = TimeOfDay(hour: 7, minute: 0);
  TimeOfDay selectedEveningTime = TimeOfDay(hour: 15, minute: 0);

  TextEditingController morningTimeController = TextEditingController();
  TextEditingController eveningTimeController = TextEditingController();

   final DatabaseReference _jamPagi =
      FirebaseDatabase().reference().child('pakan').child('pakan_pagi');
  final DatabaseReference _jamSore =
      FirebaseDatabase().reference().child('pakan').child('pakan_sore');

  String _morning = "";
  String _evening = "";

  @override
  void initState() {
    super.initState();
    fetchData();
    _updateDate();
    Timer.periodic(Duration(minutes: 1), (timer) {
      checkAndUpdateStatus();
    });
  }

Future fetchData() async {
  try {
    DatabaseEvent eventPagi = await _jamPagi.once();
    DatabaseEvent eventSore = await _jamSore.once();

    if (eventPagi.snapshot.value != null &&
        eventSore.snapshot.value != null ) {
      setState(() {
        _morning = eventPagi.snapshot.value.toString();
        _evening = eventSore.snapshot.value.toString();
      });

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

Future<void> checkAndUpdateStatus() async {
  final now = DateTime.now();
  final currentHour = now.hour;
  final currentMinute = now.minute;

  final jamPagiParts = _morning.split(":");
  final jamSoreParts = _evening.split(":");

  if (jamPagiParts.length == 2 && jamSoreParts.length == 2) {
    final jamPagiHour = int.parse(jamPagiParts[0]);
    final jamPagiMinute = int.parse(jamPagiParts[1]);

    final jamSoreHour = int.parse(jamSoreParts[0]);
    final jamSoreMinute = int.parse(jamSoreParts[1]);

    final jamPagiTime = TimeOfDay(hour: jamPagiHour, minute: jamPagiMinute);
    final jamSoreTime = TimeOfDay(hour: jamSoreHour, minute: jamSoreMinute);

    bool shouldUpdateStatus = (currentHour == jamPagiHour && currentMinute == jamPagiMinute) ||
      (currentHour == jamSoreHour && currentMinute == jamSoreMinute);

    if ((currentHour == jamPagiTime.hour && currentMinute == jamPagiTime.minute) ||
        (currentHour == jamSoreTime.hour && currentMinute == jamSoreTime.minute)) {
      DatabaseReference databaseReference = FirebaseDatabase.instance.reference().child('pakan');
      await databaseReference.update({'motor_status': shouldUpdateStatus});

    }
  }
}

  void _showDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min, // Adjust the size of the AlertDialog
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "Ubah Jadwal Makan",
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                    ),
                    buildTimeInput(
                      "Jam Makan Pagi",
                      selectedMorningTime,
                      morningTimeController,
                    ),
                    buildTimeInput(
                      "Jam Makan Sore",
                      selectedEveningTime,
                      eveningTimeController,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        ElevatedButton(
                          onPressed: () async {
                            setState(() {
                              selectedMorningTime = TimeOfDay(hour: int.parse(morningTimeController.text.split(":")[0]), minute: int.parse(morningTimeController.text.split(":")[1]));
                              selectedEveningTime = TimeOfDay(hour: int.parse(eveningTimeController.text.split(":")[0]), minute: int.parse(eveningTimeController.text.split(":")[1]));
                            });
                            await savePakanToFirebase(
                                morningTimeController.text, eveningTimeController.text);
                                await fetchData();
                            Navigator.pop(context);
                          },
                          child: Text("Save"),
                        ),
                        ElevatedButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text("Back"),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget buildTimeInput(
      String label, TimeOfDay selectedTime, TextEditingController controller) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            offset: Offset(0, 3),
            blurRadius: 5,
            spreadRadius: 0,
          ),
        ],
      ),
      child: InkWell(
        onTap: () async {
          TimeOfDay? time = await showTimePicker(
            context: context,
            initialTime: selectedTime,
          );
          if (time != null) {
            String formattedTime =
                "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}";
            controller.text = formattedTime;
          }
        },
        child: TextField(
          controller: controller,
          decoration: InputDecoration(
            labelText: label,
            suffixIcon: Icon(Icons.access_time),
          ),
          enabled: false,
        ),
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    
    morningTimeController.text =
        "${selectedMorningTime.hour.toString().padLeft(2, '0')}:${selectedMorningTime.minute.toString().padLeft(2, '0')}";
    eveningTimeController.text =
        "${selectedEveningTime.hour.toString().padLeft(2, '0')}:${selectedEveningTime.minute.toString().padLeft(2, '0')}";

    return Scaffold(
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 30, right: 30, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  "Hari ini",
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                Text(
                   currentDate,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                
                buildTimeDisplay("Makan Pagi", _morning),
                buildTimeDisplay("Makan Sore", _evening),
                Container(
                  padding: EdgeInsets.only(top: 25, left: 134),
                  child: MaterialButton(
                    elevation: 0,
                    onPressed: () {
                      _showDialog(context);
                    },
                    child: Text(
                      "Ubah",
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Colors.orange,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 151.5),
                  child: Center(
                      child: Text(
                    "Copyright @2023 Team Dev MBKM All Right Reserved",
                    style: TextStyle(fontSize: 11),
                  )),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buildTimeDisplay(String label, String time) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      padding: EdgeInsets.all(10),
      width: MediaQuery.of(context).size.width,
      height: 180,
      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(
                  label,
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          Divider(),
          Container(
            child: Text(
              time,
              style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }
}
