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

import 'services/notif_service.dart';
import 'main_navigation.dart';
import 'screens/login_page.dart';

late final DatabaseReference db;

/// 🔥 TIMER NOTIF
int lastNotifTime = 0;

/// 🔥 BACKGROUND HANDLER (opsional)
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Notif background: ${message.notification?.title}");
}

/// 🔥 AMBIL TOKEN FCM (opsional)
Future<void> initFCM() async {
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  await messaging.requestPermission();

  String? token = await messaging.getToken();

  print("TOKEN FCM: $token");
}

/// 🔥 LISTENER GLOBAL (FINAL TIMER)
void listenDeteksi() {
  db.child("Kebun/Klasifikasi").onValue.listen((event) {
    final data = event.snapshot.value;

    if (data == null) return;

    String status = data.toString().trim().toLowerCase();

    print("GLOBAL DETEKSI: $status");

    int now = DateTime.now().millisecondsSinceEpoch;

    /// 🔔 NOTIF TIAP 10 DETIK SELAMA BURUNG
    if (status == "burung") {
      if (now - lastNotifTime > 5000) {
        // ⏱️ 10 detik
        lastNotifTime = now;

        NotifService.showNotif("⚠️ Hama Burung!", "Burung terdeteksi di kebun");
      }
    }
  });
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  // 🔥 INIT NOTIFIKASI LOKAL
  await NotifService.init();

  // 🔥 FCM (opsional)
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await initFCM();

  // 🔥 INIT DATABASE
  final database = FirebaseDatabase.instanceFor(
    app: Firebase.app(),
    databaseURL:
        "https://tugas-akhir-9947b-default-rtdb.asia-southeast1.firebasedatabase.app",
  );

  db = database.ref();

  // 🔥 AKTIFKAN LISTENER GLOBAL
  listenDeteksi();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          if (snapshot.hasData) {
            return const MainNavigation();
          }

          return const LoginPage();
        },
      ),
    );
  }
}
