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

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

  @override
  State<ManualScreen> createState() => _ManualScreenState();
}

class _ManualScreenState extends State<ManualScreen> {

  /// ✅ WAJIB: pakai database yang sama dengan Dashboard
  final dbRef = FirebaseDatabase.instanceFor(
    app: Firebase.app(),
    databaseURL: "https://tomat2-default-rtdb.asia-southeast1.firebasedatabase.app",
  ).ref();

  bool pumpOn = false;
  String mode = "";

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

    /// ===== LISTEN PUMP =====
    dbRef.child("control/pump").onValue.listen((event) {
      print("PUMP: ${event.snapshot.value}");

      final data = event.snapshot.value;

      setState(() {
        pumpOn = data.toString() == "1";
      });
    });

    /// ===== LISTEN MODE =====
    dbRef.child("control/mode").onValue.listen((event) {
      print("MODE: ${event.snapshot.value}");

      setState(() {
        mode = event.snapshot.value.toString();
      });
    });
  }

  /// ===== TOGGLE PUMP =====
  void togglePump() async {

    /// BLOCK kalau bukan manual
    if (mode != "manual") {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("Mode AUTO aktif, tidak bisa kontrol manual"),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    int newValue = pumpOn ? 0 : 1;

    await dbRef.child("control/pump").set(newValue);
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: const Color(0xFF0F172A),

      appBar: AppBar(
        title: const Text("Manual Control"),
        backgroundColor: const Color(0xFF0F172A),
        elevation: 0,
      ),

      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            /// ===== MODE INDICATOR =====
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: mode == "manual"
                    ? Colors.greenAccent.withOpacity(0.2)
                    : Colors.orangeAccent.withOpacity(0.2),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                "MODE: ${mode.isEmpty ? "..." : mode.toUpperCase()}",
                style: TextStyle(
                  color: mode == "manual"
                      ? Colors.greenAccent
                      : Colors.orangeAccent,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),

            const SizedBox(height: 30),

            /// ===== TITLE =====
            const Text(
              "POMPA AIR",
              style: TextStyle(
                fontSize: 22,
                color: Colors.white70,
                letterSpacing: 1.5,
              ),
            ),

            const SizedBox(height: 30),

            /// ===== BUTTON =====
            GestureDetector(
              onTap: togglePump,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                height: 180,
                width: 180,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: pumpOn
                      ? const LinearGradient(
                          colors: [Colors.tealAccent, Colors.greenAccent],
                        )
                      : const LinearGradient(
                          colors: [Colors.grey, Colors.black45],
                        ),
                  boxShadow: pumpOn
                      ? [
                          BoxShadow(
                            color: Colors.greenAccent.withOpacity(0.6),
                            blurRadius: 30,
                            spreadRadius: 5,
                          )
                        ]
                      : [],
                ),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        pumpOn ? Icons.power : Icons.power_off,
                        size: 50,
                        color: Colors.black,
                      ),
                      const SizedBox(height: 10),
                      Text(
                        pumpOn ? "ON" : "OFF",
                        style: const TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 30),

            /// ===== STATUS =====
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              decoration: BoxDecoration(
                color: const Color(0xFF1E293B),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.water_drop,
                    color: pumpOn
                        ? Colors.greenAccent
                        : Colors.redAccent,
                  ),
                  const SizedBox(width: 10),
                  Text(
                    pumpOn ? "PUMP ACTIVE" : "PUMP OFF",
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )
                ],
              ),
            ),

            const SizedBox(height: 40),

            /// ===== INFO =====
            Text(
              mode == "manual"
                  ? "Tap to control pump manually"
                  : "Manual control disabled in AUTO mode",
              style: TextStyle(
                color: Colors.white.withOpacity(0.5),
              ),
            )
          ],
        ),
      ),
    );
  }
}