import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:generp/Notifiers/AttendanceNotifier.dart';
import 'package:generp/Notifiers/CheckInProvider.dart';
import 'package:generp/Notifiers/Counter.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Notifiers/InventoryProvider.dart';
import 'package:generp/Notifiers/LogoutNotifier.dart';
import 'package:generp/Notifiers/PCWalletProvider.dart';
import 'package:generp/Notifiers/PaymentCollectionProvider.dart';
import 'package:generp/Notifiers/PaymentDetailsProvider.dart';
import 'package:generp/Notifiers/PendingComplaintsProvider.dart';
import 'package:generp/Notifiers/ProfileNotifier.dart';
import 'package:generp/Notifiers/ServiceEngineerDashboardProvider.dart';
import 'package:generp/Notifiers/TodayMontlyVisitsProvider.dart';
import 'package:generp/Notifiers/VisitDetailsProvider.dart';
import 'package:generp/Notifiers/loginNotifier.dart';
import 'package:generp/Notifiers/splashVersionNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/HomeScreen.dart';
import 'package:generp/screens/splash.dart';
import 'package:provider/provider.dart';

const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'generp_channel', // id
    'generp_channel_name',
    importance: Importance.max,
    playSound: false);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  String type = message.data['type'] ?? '';

  if (type == 'offline_reminder') {
    FlutterRingtonePlayer().play(
      fromAsset: "assets/offline_reminder.mp3",
      ios: IosSounds.glass, // Specify the iOS sound
    );
  } else if (type == 'normal') {
    FlutterRingtonePlayer().play(
      fromAsset: "assets/notification_sound.mp3",
      ios: IosSounds.glass, // Specify the iOS sound
    );
  } else if (type == 'web_erp_notification') {
    FlutterRingtonePlayer().play(
      fromAsset: "assets/notification_sound.mp3",
      ios: IosSounds.glass, // Specify the iOS sound
    );
  } else {
    FlutterRingtonePlayer().play(
        fromAsset: "assets/notification_sound.mp3",
        // will be the sound on Android
        ios: IosSounds.glass // will be the sound on iOS
    );
  }
  if(kDebugMode){
    print('A Background message just showed up: ${message.messageId}');
  }

}

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  if(kDebugMode){
    if (Firebase.apps.isNotEmpty) {
      print("Firebase is initialized");
    } else {
      print("Firebase is not initialized");
    }
  }


  if (Platform.isAndroid) {
    await Firebase.initializeApp(
      options: FirebaseOptions(
        apiKey: "AIzaSyBmkmKdYfBt2n5QRlmZJ9MV_Amh9xR3UOY",
        appId: "1:329382566569:android:26dc8519537b04deff67b8",
        messagingSenderId: "329382566569",
        projectId: "generp-fe09d",
      ),
    );
  } else if (Platform.isIOS) {
    await Firebase.initializeApp();
  }

  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: true,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: false,
  );
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    print("msg");
    String type = message.data['type'] ?? '';
    if (type == 'offline_reminder') {
      FlutterRingtonePlayer().play(
        fromAsset: "assets/offline_reminder.mp3",
        ios: IosSounds.glass, // Specify the iOS sound
      );
    } else if (type == 'normal') {
      FlutterRingtonePlayer().play(
        fromAsset: "assets/notification_sound.mp3",
        ios: IosSounds.glass, // Specify the iOS sound
      );
    } else if (type == 'web_erp_notification') {
      FlutterRingtonePlayer().play(
        fromAsset: "assets/notification_sound.mp3",
        ios: IosSounds.glass, // Specify the iOS sound
      );
    } else {
      FlutterRingtonePlayer().play(
          fromAsset:
          "assets/notification_sound.mp3", // will be the sound on Android
          ios: IosSounds.glass // will be the sound on iOS
      );
    }
  });

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );

    FirebaseMessaging.instance.getToken().then((value) {
      String? token = value;
      if(kDebugMode){
        print("fbstoken:{$token}");
      }

      SharedpreferencesService().saveString("fbstoken", token!);
    });


  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      String type = message.data['type'] ?? '';
      String redirectUrl = message.data['redirect_url'] ?? '';
     
      // Navigator.push(
      //   context,
      //   MaterialPageRoute(builder: (context) => Dashboard()),
      // );
      if(kDebugMode){
        print('A new onMessageOpenedApp event was published!');
      }

    });
    return MultiProvider(providers: [
      ChangeNotifierProvider(create: (_)=>SplashVersionNotifier()),
      ChangeNotifierProvider(create: (_)=>Loginnotifier()),
      ChangeNotifierProvider(create: (_)=>Counter()),
      ChangeNotifierProvider(create: (_)=>HomescreenNotifier()),
      ChangeNotifierProvider(create: (_)=>ProfileNotifer()),
      ChangeNotifierProvider(create: (_)=>LogoutNotifier()),
      ChangeNotifierProvider(create: (_)=>AttendanceNotifier()),
      ChangeNotifierProvider(create: (_)=>CheckInOutProvider()),
      ChangeNotifierProvider(create: (_)=>InventoryProvider()),
      ChangeNotifierProvider(create: (_)=>Serviceengineerdashboardprovider()),
      ChangeNotifierProvider(create: (_)=>Pendingcomplaintsprovider()),
      ChangeNotifierProvider(create: (_)=>Todaymontlyvisitsprovider()),
      ChangeNotifierProvider(create: (_)=>Paymentcollectionprovider()),
      ChangeNotifierProvider(create: (_)=>Visitdetailsprovider()),
      ChangeNotifierProvider(create: (_)=>Pcwalletprovider()),
      ChangeNotifierProvider(create: (_)=>Paymentdetailsprovider()),
    ],
    child: Builder(
      builder: (BuildContext context){
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            fontFamily: 'Lexend',
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            hoverColor: Colors.transparent,
            scaffoldBackgroundColor: Colors.white,
            dialogBackgroundColor: Colors.white,
            cardColor: Colors.white,
            shadowColor: Colors.white54,
            searchBarTheme: const SearchBarThemeData(),
            tabBarTheme: const TabBarTheme(),
            dialogTheme: const DialogTheme(
              shadowColor: Colors.white,
              surfaceTintColor: Colors.white,
              backgroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                    Radius.circular(5.0)), // Set the border radius of the dialog
              ),
            ),
            buttonTheme: const ButtonThemeData(),
            appBarTheme: const AppBarTheme(
              shadowColor: Colors.white,
              surfaceTintColor: Colors.white,
              color: Colors.white,
            ),
            cardTheme: const CardTheme(
              shadowColor: Colors.white,
              surfaceTintColor: Colors.white,
              color: Colors.white,
              //),
            ),
            textButtonTheme: TextButtonThemeData(
              style: ButtonStyle(
                // overlayColor: MaterialStateProperty.all(Colors.white),
              ),
            ),
            bottomSheetTheme: const BottomSheetThemeData(
                surfaceTintColor: Colors.white, backgroundColor: Colors.white),
            colorScheme: const ColorScheme.light(background: Colors.white)
                .copyWith(background: Colors.white),
          ),
          home: const Splash(),
        );
      },
    ),);
  }
}
