import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'screens/splash.dart'; // Import splash.dart
import 'firebase_options.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'background_service.dart'; // Import the background service
import 'package:firebase_app_check/firebase_app_check.dart';
import 'services/notification_service.dart'; // Import layanan notifikasi baru
import 'services/history_service.dart'; // Import layanan history
// Pastikan path ini sesuai

// Initialize the FlutterLocalNotificationsPlugin
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

Future<void> main() async {
  try {
    WidgetsFlutterBinding.ensureInitialized(); // Pastikan Flutter binding sudah diinisialisasi
    
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

     // Tambahkan ini setelah Firebase.initializeApp()
   await FirebaseAppCheck.instance.activate(
     // Untuk Android
     androidProvider: AndroidProvider.playIntegrity,
   );
    
    
    // Initialize local notifications
    const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
    
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // Tampilkan notifikasi saat aplikasi aktif
      _showNotification(message);
    });
    
    backgroundService(); // Start the background service
    
    // Inisialisasi layanan notifikasi untuk monitoring suhu dan kelembapan
    await NotificationService().initialize();
    print("✅ Layanan notifikasi suhu dan kelembapan berhasil diinisialisasi");
    
    // Inisialisasi layanan history untuk pencatatan data history
    await HistoryService().initialize();
    print("✅ Layanan history berhasil diinisialisasi");
    
    runApp(MyApp());
  } catch (e) {
    print('Error initializing Firebase: $e');
    // You might want to show an error screen instead
    runApp(ErrorApp());
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Jago',
      home: SplashScreen(), // Set SplashScreen sebagai halaman awal
    );
  }
}

// Add an error app widget to handle initialization failures
class ErrorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Text(
            'Failed to initialize app. Please check your connection and try again.',
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}

Future<void> _showNotification(RemoteMessage message) async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'Jago',
    'Notification',
    channelDescription: 'Cek Notification!!!',
    importance: Importance.max,
    priority: Priority.high,
  );
  const NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
  
  await flutterLocalNotificationsPlugin.show(
    0,
    message.notification?.title,
    message.notification?.body,
    platformChannelSpecifics,
    payload: 'item x',
  );
}

