import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'jadwal_page.dart';
import 'notifikasi_page.dart';
import 'manual_page.dart';

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

  @override
  State<MenuUtama> createState() => _MenuUtamaState();
}

class _MenuUtamaState extends State<MenuUtama> {

  // 🔥 REALTIME DATABASE
  final dbRef = FirebaseDatabase.instance.ref("sensor");

  double berat1 = 0;
  double berat2 = 0;
  double jarak = 0;

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

    dbRef.onValue.listen((event) {
      final data = event.snapshot.value as Map?;

      if (data != null) {
        setState(() {
          berat1 = (data['berat1'] ?? 0).toDouble();
          berat2 = (data['berat2'] ?? 0).toDouble();
          jarak = (data['jarak'] ?? 0).toDouble();
        });
      }
    });
  }

  // 🔐 CHECK PASSWORD
  Future<bool> checkPassword(String input) async {
    try {
      final doc = await FirebaseFirestore.instance
          .collection('settings')
          .doc('admin')
          .get();

      return input == doc['password'];
    } catch (e) {
      print("Error Firestore: $e");
      return false;
    }
  }

  void showPasswordDialogManual(BuildContext context) {
  TextEditingController controller = TextEditingController();

  showDialog(
    context: context,
    barrierColor: Colors.black.withOpacity(0.3),
    builder: (_) => Center(
      child: Container(
        width: 300,
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(20),
        ),
        child: Material(
          color: Colors.transparent,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                "Password",
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),

              const SizedBox(height: 10),

              const Text(
                "Isi Password Untuk Masuk",
                style: TextStyle(fontSize: 12),
              ),

              const SizedBox(height: 20),

              TextField(
                controller: controller,
                obscureText: true,
                decoration: InputDecoration(
                  hintText: "Kata Sandi",
                  filled: true,
                  fillColor: Colors.grey[300],
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ),

              const SizedBox(height: 20),

              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () async {
                    bool valid =
                        await checkPassword(controller.text);

                    if (valid) {
                      Navigator.pop(context);

                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => const ManualPage(),
                        ),
                      );
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text("Password salah"),
                        ),
                      );
                    }
                  },
                  child: const Text("Masuk"),
                ),
              ),
            ],
          ),
        ),
      ),
    ),
  );
}

  // 🔐 POPUP PASSWORD
  void showPasswordDialog(BuildContext context) {
    TextEditingController controller = TextEditingController();

    showDialog(
      context: context,
      barrierColor: Colors.black.withOpacity(0.3),
      builder: (_) => Center(
        child: Container(
          width: 300,
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(20),
          ),
          child: Material(
            color: Colors.transparent,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  "Password",
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),

                const SizedBox(height: 10),

                const Text(
                  "Isi Password Untuk Masuk",
                  style: TextStyle(fontSize: 12),
                ),

                const SizedBox(height: 20),

                TextField(
                  controller: controller,
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: "Kata Sandi",
                    filled: true,
                    fillColor: Colors.grey[300],
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                ),

                const SizedBox(height: 20),

                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFFFFD54F),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                    onPressed: () async {
                      bool valid =
                          await checkPassword(controller.text);

                      if (valid) {
                        Navigator.pop(context);

                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (_) => const JadwalPage(),
                          ),
                        );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(
                            content: Text("Password salah"),
                          ),
                        );
                      }
                    },
                    child: const Text("Masuk"),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 🔥 CARD PENAMPUNG PAKAN UTAMA
// 🔥 CARD PENAMPUNG PAKAN UTAMA
Widget penampungPakanCard() {

double persen;

if (jarak <= 10) {
  persen = 15 + ((10 - jarak) / (10 - 3)) * 85;
} else {
  persen = ((12 - jarak) / (12 - 10)) * 15;
}

if (persen < 0) persen = 0;
if (persen > 100) persen = 100;

  Color warna;

  if (persen > 60) {
    warna = Colors.green;
  } else if (persen > 30) {
    warna = Colors.orange;
  } else {
    warna = Colors.red;
  }

  return Container(
    width: double.infinity,
    margin: const EdgeInsets.only(bottom: 15),
    padding: const EdgeInsets.all(15),
    decoration: BoxDecoration(
      color: const Color(0xFFFFC107),
      borderRadius: BorderRadius.circular(15),
      boxShadow: [
        BoxShadow(
          color: Colors.black.withOpacity(0.1),
          blurRadius: 5,
        )
      ],
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [

        const Text(
          "Wadah Penampung Pakan:",
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),

        const SizedBox(height: 20),

        Center(
          child: Stack(
            clipBehavior: Clip.none,
            children: [

              Container(
                width: 120,
                height: 50,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.black,
                    width: 3,
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),

              Positioned(
                left: 3,
                top: 3,
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 500),
                  width: (persen / 100) * 110,
                  height: 40,
                  decoration: BoxDecoration(
                    color: warna,
                    borderRadius: BorderRadius.circular(6),
                  ),
                ),
              ),

              Positioned(
                right: -10,
                top: 15,
                child: Container(
                  width: 8,
                  height: 20,
                  decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(3),
                  ),
                ),
              ),

              SizedBox(
                width: 120,
                height: 50,
                child: Center(
                  child: Text(
                    "${persen.toStringAsFixed(0)}%",
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

  // 🔶 CARD INFO BERAT
// 🔶 CARD INFO BERAT
Widget infoCard(String title, double berat) {

  return Container(
    width: double.infinity,
    margin: const EdgeInsets.only(bottom: 15),
    padding: const EdgeInsets.all(15),
    decoration: BoxDecoration(
      color: const Color(0xFFFFC107),
      borderRadius: BorderRadius.circular(15),
      boxShadow: [
        BoxShadow(
          color: Colors.black.withOpacity(0.1),
          blurRadius: 5,
        )
      ],
    ),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [

        Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),

        Container(
          padding: const EdgeInsets.symmetric(
            horizontal: 12,
            vertical: 6,
          ),
          decoration: BoxDecoration(
            color: Colors.orange,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            "${berat.toStringAsFixed(0)} Gram",
            style: const TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    ),
  );
}

  // 🔶 CARD JADWAL
  Widget jadwalCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: const Color(0xFFFFC107),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          const Text(
            "Jadwal Pakan:",
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),

          const SizedBox(height: 10),

          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.orange,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text(
              "Pagi Jam: 09.00 WIB",
              style: TextStyle(color: Colors.white),
            ),
          ),

          const SizedBox(height: 8),

          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.orange,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text(
              "Sore Jam: 15.00 WIB",
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFE0E0E0),

      body: SafeArea(
        child: Column(
          children: [

            // 🔶 HEADER
            Container(
              width: double.infinity,
              margin: const EdgeInsets.all(16),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFFFE082),
                borderRadius: BorderRadius.circular(25),
                boxShadow: [
                  BoxShadow(
                    color: Colors.orange.withOpacity(0.3),
                    blurRadius: 15,
                    offset: const Offset(0, 5),
                  )
                ],
              ),
              child: Column(
                crossAxisAlignment:
                    CrossAxisAlignment.start,
                children: [

                        // 🔥 TITLE + NOTIFIKASI
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [

                  const Text(
                    "Menu Utama",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),

                            // 🔔 TOMBOL NOTIFIKASI
          // 🔔 TOMBOL NOTIFIKASI
          Container(
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.7),
              shape: BoxShape.circle,
            ),
            child: IconButton(
              onPressed: () {

                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (_) => const NotifikasiPage(),
                  ),
                );

              },
              icon: const Icon(
                Icons.notifications,
                color: Colors.black,
              ),
            ),
          ),
        ],
      ),

                  const SizedBox(height: 15),

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [

    // Jadwal Pakan
    SizedBox(
      width: 100,
      child: GestureDetector(
        onTap: () => showPasswordDialog(context),
        child: Column(
          children: [
            CircleAvatar(
              radius: 30,
              backgroundColor: Colors.grey[300],
              child: const Icon(
                Icons.description,
                size: 30,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              "Jadwal Pakan",
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    ),

    // Manual Pakan
    SizedBox(
      width: 100,
      child: GestureDetector(
        onTap: () => showPasswordDialogManual(context),
        child: Column(
          children: [
            CircleAvatar(
              radius: 30,
              backgroundColor: Colors.grey[300],
              child: const Icon(
                Icons.restaurant,
                size: 30,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              "Manual Pakan",
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    ),

  ],
),
                ],
              ),
            ),

            const Padding(
              padding:
                  EdgeInsets.symmetric(horizontal: 16),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  "Update Hari Ini!!",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ),
            ),

            const SizedBox(height: 10),

            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                ),
                child: Column(
                  crossAxisAlignment:
                      CrossAxisAlignment.start,
                  children: [

                    // 🔥 PENAMPUNG PAKAN
                    penampungPakanCard(),

                    // 🔥 WADAH KANAN & KIRI
                    infoCard(
                      "Wadah Pakan Kanan:",
                      berat1,
                    ),

                    infoCard(
                      "Wadah Pakan Kiri:",
                      berat2,
                    ),

                    const SizedBox(height: 10),

                    // 🔥 JADWAL
                    jadwalCard(),

                    const SizedBox(height: 100),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}