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/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:generp/Utils/app_colors.dart';
import 'screens/notifierExports.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/splash.dart';
import 'package:provider/provider.dart';
import 'Utils/commonWidgets.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 (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();
  }
  if (kDebugMode) {
    if (Firebase.apps.isNotEmpty) {
      print("Firebase is initialized");
    } else {
      print("Firebase is not initialized");
    }
  }

  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,
  );

  await 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) {
    // SystemChrome.setApplicationSwitcherDescription(ApplicationSwitcherDescription());
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    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: (_) => UpdatePasswordProvider()),
        ChangeNotifierProvider(create: (_) => Scanloginprovider()),
        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()),
        ChangeNotifierProvider(create: (_) => Generatordetailsprovider()),
        ChangeNotifierProvider(create: (_) => Nearbygeneratorsprovider()),

        ///finance
        ChangeNotifierProvider(create: (_) => Dashboardprovider()),
        ChangeNotifierProvider(create: (_) => Requestionlistprovider()),
        ChangeNotifierProvider(create: (_) => Requesitionlidtdetailsprovider()),
        ChangeNotifierProvider(
          create: (_) => Paymentrequisitionpaymentslistprovider(),
        ),
        ChangeNotifierProvider(create: (_) => Paymentreceiptsprovider()),
        ChangeNotifierProvider(create: (_) => Commonpagesprovider()),
        ChangeNotifierProvider(create: (_) => Accountslistprovider()),
        ChangeNotifierProvider(create: (_) => Accountdetailsprovider()),
        ChangeNotifierProvider(create: (_) => Accountledgerprovider()),
        ChangeNotifierProvider(create: (_) => Pagesdashboardprovider()),
        ChangeNotifierProvider(create: (_) => Paymentsprovider()),
        ChangeNotifierProvider(create: (_) => Tpcagentsprovider()),
        ChangeNotifierProvider(create: (_) => Addpaymentprovider()),
        ChangeNotifierProvider(create: (_) => Addorderprovider()),
        ChangeNotifierProvider(create: (_) => Editpaymentprovider()),

        ///crm
        ChangeNotifierProvider(create: (_) => Crmdashboardprovider()),
        ChangeNotifierProvider(create: (_) => Leadlistprovider()),
        ChangeNotifierProvider(create: (_) => crmLeadDetailsProvider()),
        ChangeNotifierProvider(create: (_) => Editcrmaccountdetailsprovider()),
        ChangeNotifierProvider(create: (_) => Editproductlistprovider()),
        ChangeNotifierProvider(create: (_) => ProspectListProvider()),
        ChangeNotifierProvider(create: (_) => crmProspectDetailsProvider()),
        ChangeNotifierProvider(create: (_) => crmNearbyOpenLeadsProvider()),
        ChangeNotifierProvider(create: (_) => Crmgeneratequotationprovider()),
        ChangeNotifierProvider(create: (_) => Crmeditprospectaccountprovider()),
        ChangeNotifierProvider(create: (_) => Addprospectleadsprovider()),
        ChangeNotifierProvider(create: (_) => Editorderprovider()),
        ChangeNotifierProvider(create: (_) => Dispatchorderprovider()),
        ChangeNotifierProvider(create: (_) => followUpUpdateProvider()),
        ChangeNotifierProvider(create: (_) => Appointmentcalendarprovider()),
        ChangeNotifierProvider(create: (_) => Addnewleadsandprospectsprovider()),
      ],
      child: Builder(
        builder: (BuildContext context) {
          return MaterialApp(
            navigatorObservers: [MyNavigatorObserver()],
            builder: (BuildContext context, Widget? child) {
              final MediaQueryData data = MediaQuery.of(context);
              return MediaQuery(
                data: data.copyWith(textScaler: TextScaler.linear(1.0)),
                child: child ?? Container(),
              );
            },
            themeMode: ThemeMode.light,
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              fontFamily: 'JakartaRegular',
              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 TabBarThemeData(),

              textSelectionTheme: TextSelectionThemeData(
                cursorColor: AppColors.app_blue,
              ),
              dialogTheme: const DialogThemeData(
                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 CardThemeData(
                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,
                dragHandleColor: Color(0xFFe4e4e4),
                dragHandleSize: Size(60.0, 6.0),
              ),
              colorScheme: const ColorScheme.light(
                background: Colors.white,
              ).copyWith(background: Colors.white),
              scrollbarTheme: ScrollbarThemeData(
                minThumbLength: 20,
                interactive: true,
                radius: Radius.circular(6),
                thickness: WidgetStatePropertyAll(10),
                thumbColor: WidgetStateProperty.all(
                  AppColors.grey_semi.withOpacity(0.6),
                ),
              ),
              checkboxTheme: CheckboxThemeData(

                side: BorderSide(width: 0.5),
                checkColor: WidgetStatePropertyAll(AppColors.white),

              ),
              useMaterial3: true,
              // inputDecorationTheme: InputDecorationTheme(
              //   hintStyle: TextStyle(
              //     fontWeight: FontWeight.w400,
              //     color: Color(0xFFB4BEC0),
              //     fontSize: 14,
              //   ),
              //
              //   enabledBorder: InputBorder.none,
              //   focusedBorder: InputBorder.none,
              // ),
            ),
            home: const Splash(),
          );
        },
      ),
    );
  }
}
