import 'dart:async';
import 'dart:ui';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'firebase_options.dart';

Future<void> initializeService() async {

  final service = FlutterBackgroundService();

  await service.configure(

    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      autoStartOnBoot: true,
      isForegroundMode: true,

      notificationChannelId: "door_security_service",
      initialNotificationTitle: "Door Security",
      initialNotificationContent: "Monitoring RFID Door...",
      foregroundServiceNotificationId: 888,
    ),

    iosConfiguration: IosConfiguration(),

  );

  await service.startService();
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {

  DartPluginRegistrant.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  final FlutterLocalNotificationsPlugin notif =
      FlutterLocalNotificationsPlugin();

  const AndroidInitializationSettings android =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  const InitializationSettings settings =
      InitializationSettings(android: android);

  await notif.initialize(settings: settings);

  final rtdb = FirebaseDatabase.instance.ref();

  bool reminderEnabled = true;
  int reminderHour = 21;
  int reminderMinute = 0;


  /// listen reminder setting
  rtdb.child("rfid/reminder").onValue.listen((event) {

    if (event.snapshot.value == null) return;

    Map data = Map.from(event.snapshot.value as Map);

    reminderEnabled = data["enabled"] ?? true;
    reminderHour = data["hour"] ?? 21;
    reminderMinute = data["minute"] ?? 0;

  });

  /// keep alive log
  Timer.periodic(const Duration(minutes: 1), (timer) {
    print("Background Service Running");
  });

  /// RFID notification listener
  rtdb.child("rfid/notification").onValue.listen((event) async {

    try {

      final value = event.snapshot.value;

      if (value == null) return;

      String data = value.toString();

      if (data != "ACCESS_DENIED") return;

      const AndroidNotificationDetails androidDetails =
          AndroidNotificationDetails(
        "door_security",
        "Door Security",
        importance: Importance.max,
        priority: Priority.high,
        playSound: true,
        enableVibration: true,
      );

      const NotificationDetails details =
          NotificationDetails(android: androidDetails);

      await notif.show(
        id: DateTime.now().millisecondsSinceEpoch ~/ 1000,
        title: "🚨 ACCESS DENIED",
        body: "RFID card tidak terdaftar",
        notificationDetails: details,
      );

      await rtdb.child("rfid/notification").set("IDLE");

    } catch (e) {

      print("SERVICE ERROR: $e");

    }

  });

  /// ================= DOOR REMINDER =================
bool reminderAlreadyShown = false;

Timer.periodic(const Duration(seconds: 20), (timer) async {

  try {

    if (!reminderEnabled) return;

    DateTime now = DateTime.now();

    /// 🔥 RESET SETELAH LEWAT MENIT
    if (now.minute != reminderMinute) {
      reminderAlreadyShown = false;
    }

    /// 🔥 CEK SESUAI JAM
    if (now.hour == reminderHour &&
        now.minute == reminderMinute &&
        !reminderAlreadyShown) {

      final door = await rtdb.child("rfid/doorSensor").get();

      /// 🔥 JIKA PINTU TERBUKA
      if (door.value == "OPEN") {

        const AndroidNotificationDetails androidDetails =
            AndroidNotificationDetails(
          "door_security",
          "Door Security",
          importance: Importance.max,
          priority: Priority.high,
          playSound: true,
          enableVibration: true,
        );

        const NotificationDetails details =
            NotificationDetails(android: androidDetails);

        await notif.show(
          id: 999,
          title: "⚠️ DOOR WARNING",
          body: "Pintu masih terbuka, segera tutup!",
          notificationDetails: details,
        );

        /// 🔥 BIAR TIDAK SPAM DALAM 1 MENIT
        reminderAlreadyShown = true;
      }
    }

  } catch (e) {

    print("REMINDER ERROR: $e");
  }
});

}