// import 'package:firebase_app_check/firebase_app_check.dart';
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_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:nhance_partner/presentation/providers/manager_provider.dart';
import 'package:nhance_partner/presentation/providers/userRoleProvider.dart';
import 'package:nhance_partner/presentation/screens/staff/enquiry_single_page/widgets/enquiry_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'core/routing/app_router.dart';

Future<void> _restoreManagerId(WidgetRef ref) async {
  final prefs = await SharedPreferences.getInstance();
  final int? savedManagerId = prefs.getInt('managerId');
  final int? savedUserId = prefs.getInt('userId');
  final String? savedUserRole = prefs.getString('userRole');

  final String? savedAttendanceIndvStaffId = prefs.getString(
    'attendanceIndvStaff',
  );
  final String? savedAttendanceIndvStaffName = prefs.getString(
    'attendanceIndvStaffName',
  );

  if (savedManagerId != null && savedUserId != null) {
    ref.read(managerIdProvider.notifier).state = savedManagerId;
    ref.read(userIdProvider.notifier).state = savedUserId;
    ref.read(userRoleProvider.notifier).state = savedUserRole;

    print("Manager ID restored: $savedManagerId");
    print("User ID restored: $savedUserId");
    print("Role restored: $savedUserRole");
  }

  if (savedAttendanceIndvStaffId != null &&
      savedAttendanceIndvStaffName != null) {
    ref.read(staffIndiviualAttendanceIdProvider.notifier).state =
        savedAttendanceIndvStaffId;
    ref.read(staffIndiviualAttendanceNameIdProvider.notifier).state =
        savedAttendanceIndvStaffName;

    print("Staff ID restored: $savedAttendanceIndvStaffId");
    print("Staff Name restored: $savedAttendanceIndvStaffName");
  }
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // final SharedPreferences prefs = await SharedPreferences.getInstance();
  // prefs.clear();
  if (kIsWeb) {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "AIzaSyC4yHbCX4mQu0jO81pJrDwxKLQlTQWofrc",
        authDomain: "nhance-ee8d1.firebaseapp.com",
        projectId: "nhance-ee8d1",
        storageBucket: "nhance-ee8d1.firebasestorage.app",
        messagingSenderId: "1084115316849",
        appId: "1:1084115316849:web:8fc3b1c886349ae86c6bd0",
      ),
    );
  } else {
    // await Firebase.initializeApp();
    // await FirebaseAppCheck.instance.activate(
    //   // webProvider: ReCaptchaV3Provider('recaptcha-v3-site-key'),
    //   androidProvider: AndroidProvider.playIntegrity,
    //   appleProvider: AppleProvider.appAttest,
    // );
    // FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    // FirebaseMessaging messaging = FirebaseMessaging.instance;
    // // NotificationSettings settings = await messaging.requestPermission();
    // NotificationSettings settings =
    //     await FirebaseMessaging.instance.requestPermission(
    //   alert: true,
    //   badge: true,
    //   sound: true,
    // );
    // print('User granted permission: ${settings.authorizationStatus}');

    // FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    //   print('Foreground Message: ${message.notification?.title}');
    // });

    // FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    //   print('User tapped on notification');
    // });
  }

  runApp(const ProviderScope(child: MyApp()));
}

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

  @override
  ConsumerState<MyApp> createState() => _MyAppState();
}

class _MyAppState extends ConsumerState<MyApp> {
  @override
  void initState() {
    super.initState();

    if (kIsWeb) {
      Future.microtask(() => _restoreManagerId(ref));
    }
  }

  @override
  Widget build(BuildContext context) {
    // return MaterialApp(
    //   title: 'Nhance Partner',
    //   debugShowCheckedModeBanner: false,
    //   theme: ThemeData(
    //     primaryColor: const Color(0xFFb8e6e1),
    //     colorScheme: ColorScheme.fromSeed(
    //       seedColor: const Color(0xFFb8e6e1),
    //       primary: const Color(0xFF4a90e2),
    //     ),
    //     scaffoldBackgroundColor: const Color(0xFFf5f5f5),
    //     useMaterial3: true,
    //   ),
    //   home: const EnquiryScreen(),
    // );

    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      title: 'Nhance Partner',

      theme: ThemeData(
        // primarySwatch: Colors.blue,
        // primaryColor: Color(0xFFE26728), // active color (selected / focused)
        primaryColorLight: Color(0xFFEDF6F5),
        colorScheme: ColorScheme.fromSeed(
          seedColor: Color(0xFFEDF6F5), // Generates harmonious colors
        ),

        textTheme: GoogleFonts.interTextTheme(
          Theme.of(context).textTheme, // base on default styles
        ),
      ),

      routerConfig: appRouter,
    );
  }
}
