import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:initial_folder/firebase_options.dart';
import 'package:initial_folder/get_it.dart';
import 'package:initial_folder/providers/announcement_provider.dart';
import 'package:initial_folder/providers/auth_provider.dart';
import 'package:initial_folder/providers/banners_provider.dart';
import 'package:initial_folder/providers/cart_provider.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/categories_provider.dart';
import 'package:initial_folder/providers/certificate_provider.dart';
import 'package:initial_folder/providers/checkbox_provider.dart';
import 'package:initial_folder/providers/data_diri_provider.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/filters_course_provider.dart';
import 'package:initial_folder/providers/firebase_authentication_provider.dart';
import 'package:initial_folder/providers/forgot_password_provider.dart';
import 'package:initial_folder/providers/incomplete_profile_provider.dart';
import 'package:initial_folder/providers/history_transactions_provider.dart';
import 'package:initial_folder/providers/latest_course_provider.dart';
import 'package:initial_folder/providers/lesson_course_provider.dart';
import 'package:initial_folder/providers/like_announcement.dart';
import 'package:initial_folder/providers/like_or_unlike_provider.dart';
import 'package:initial_folder/providers/login_provider.dart';
import 'package:initial_folder/providers/my_course_provider.dart';
import 'package:initial_folder/providers/notification_provider.dart';
import 'package:initial_folder/providers/order_provider.dart';
import 'package:initial_folder/providers/others_course_provider.dart';
import 'package:initial_folder/providers/payments_provider.dart';
import 'package:initial_folder/providers/play_video_course_provider.dart';
import 'package:initial_folder/providers/posting_announcement_reply_provider.dart';
import 'package:initial_folder/providers/posting_qna_provider.dart';
import 'package:initial_folder/providers/posting_qna_reply_provider.dart';
import 'package:initial_folder/providers/profile_image_provider.dart';
import 'package:initial_folder/providers/promo_course_provider.dart';
import 'package:initial_folder/providers/radeem_voucher_provider.dart';
import 'package:initial_folder/providers/registrasi_google_provider.dart';
import 'package:initial_folder/providers/reset_provider.dart';
import 'package:initial_folder/providers/search_provider.dart';
import 'package:initial_folder/providers/section_lesson_provider.dart';
import 'package:initial_folder/providers/selected_title_provider.dart';
import 'package:initial_folder/providers/stream_invoice_provider.dart';
import 'package:initial_folder/providers/tab_play_course_provider.dart';
import 'package:initial_folder/providers/description_provider.dart';
import 'package:initial_folder/providers/metode_provider.dart';
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/providers/profile_provider.dart';
import 'package:initial_folder/providers/tab_provider.dart';
import 'package:initial_folder/providers/top_course_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/providers/update_data_diri_provider.dart';
import 'package:initial_folder/providers/update_password_provider.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
import 'package:initial_folder/providers/whislist_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/providers/wishlist_post_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
// import 'package:initial_folder/screens/home/components/notification.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/services/all_certificate_service.dart';
import 'package:initial_folder/services/announcement_service.dart';
import 'package:initial_folder/services/banners_service.dart';
import 'package:initial_folder/services/cart_service.dart';
import 'package:initial_folder/services/categories_service.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:initial_folder/services/history_transactions_service.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
import 'package:initial_folder/services/notification_service.dart';
import 'package:initial_folder/services/payment_service.dart';
import 'package:initial_folder/services/search_service.dart';
import 'package:initial_folder/services/user_info_service.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/routes.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:responsive_framework/responsive_framework.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/providers/detail_invoice_provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

// Import library dan provider yang dibutuhkan untuk seluruh aplikasi

// Fungsi handler untuk pesan notifikasi Firebase yang diterima saat aplikasi di background
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // Jika ingin menggunakan service Firebase lain di background, inisialisasi dulu
  // print pesan jika mode debug
}

final globalScaffoldKey = GlobalKey<ScaffoldState>();
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await FirebaseMessaging.instance.getToken();
  setup();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  FirebaseMessaging.onMessageOpenedApp.listen((event) {
    if (kDebugMode) {
      print(event);
    }
    if (event.data['route'] == "/cart") {
      navigatorKey.currentState?.push(MaterialPageRoute(
        builder: (context) => const CartPage(),
      ));
    } else if (event.data['route'] == "/play_course") {
      navigatorKey.currentState?.push(
        MaterialPageRoute(
          builder: (context) => MultiProvider(
            providers: [
              ChangeNotifierProvider(
                create: (context) => LessonCourseProvider(
                  lessonCourseService: LessonCourseService(),
                  id: int.parse(event.data['id_course'] ?? '0'),
                ),
              ),
              ChangeNotifierProvider(
                  create: (context) => DetailCourseProvider(
                      courseService: CourseService(),
                      id: event.data['id_course'] ?? '1'))
            ],
            child: PlayCourse(
              judul: event.data['title'] ?? '',
              instruktur: event.data['instructur_name'] ?? '',
              thumbnail: event.data['thumbnail'] ??
                  "$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg",
              courseeid: event.data['id_course'],
              isQna: true,
            ),
          ),
        ),
      );
    }
  });
  ThemeProvider themeProvider = ThemeProvider();
  await themeProvider.loadTheme();
  runApp(MyApp(themeProvider: themeProvider));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key, required this.themeProvider}) : super(key: key);

  final ThemeProvider themeProvider;

  @override
  Widget build(BuildContext context) {
    // Provider untuk Theme agar bisa diakses seluruh aplikasi
    return ChangeNotifierProvider<ThemeProvider>.value(
      value: themeProvider,
      child: MultiProvider(
        // MultiProvider: daftar semua provider yang digunakan di aplikasi
        providers: [
          ChangeNotifierProvider(
            create: (context) => ThemeProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => StreamInvoiceProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => TabProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => DetailInvoiceProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => SelectedTitleProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => LikeOrUnlikeProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => LikeOrAnnouncementProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => AnnouncementProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => PostingQnaReplyProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => PostingAnnouncementReplyProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => ForgotPasswordProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => PostingQnaProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => DataDiriProvider(
              userInfoService: UserInfoService(),
            ),
          ),
          ChangeNotifierProvider(
            create: (context) => UpdateDataDiriProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => UpdatePasswordProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => TabPlayCourseProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => SectionLessonProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => PageProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => ProfileImageProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => WishlistPostProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => ProfileProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => CheckboxProvider(),
          ),
          ChangeNotifierProvider(
              create: (context) => UserInfoProvider(
                    userInfoService: UserInfoService(),
                  )),
          ChangeNotifierProvider(
              create: (context) => NotificationProvider(
                    notificationServices: NotificationServices(),
                  )),
          ChangeNotifierProvider(
            create: (context) => DescriptionProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => TotalPriceProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => MetodeProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => FirebaseAuthenticationProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => RegistrasiGoogleProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => RegistrasiGoogleProvider(),
          ),
          ChangeNotifierProvider(create: (context) => ResetProvider()),
          ChangeNotifierProvider(
            create: (context) => AuthProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                CategoriesProvider(categoriesService: CategoriesService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                BannersProvider(bannersService: BannersService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                OthersCourseProvider(otherCourseService: CourseService()),
          ),
          ChangeNotifierProvider(
            create: (context) => CartsProvider(cartService: CartService()),
          ),
          ChangeNotifierProvider(
            create: (context) => CartProvider(cartService: CartService()),
          ),
          ChangeNotifierProvider<WishlistProvider>(
            create: (context) => WishlistProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) => PaymentsProvider(
              paymentServices: PaymentServices(),
            ),
          ),
          ChangeNotifierProvider(
            create: (context) => PlayVideoCourseProvider(),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                MyCourseProvider(courseService: CourseService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                FilterCourseProvider(searchService: SearchService()),
          ),
          ChangeNotifierProvider(
            create: (context) => SearchProvider(searchService: SearchService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                TopCourseProvider(courseService: CourseService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                LatestCourseProvider(courseService: CourseService()),
          ),
          ChangeNotifierProvider(
            create: (context) =>
                PromoCourseProvider(courseService: CourseService()),
          ),
          ChangeNotifierProvider(create: (context) => OrderProvider()),
          ChangeNotifierProvider(create: (context) => LoginProvider()),
          ChangeNotifierProvider(
              create: (context) => CertificateProvider(
                  certificateServices: AllCertificateServices())),
          ChangeNotifierProvider(create: (context) => RadeemVoucherProvider()),
          ChangeNotifierProvider(
              create: (context) => IncompleteProfileProvider(
                    userInfoService: UserInfoService(),
                  )),
          ChangeNotifierProvider(
              create: (context) => HistoryTranscationsProvider(
                  historyTransactionService: HistoryTransactionService()))
        ],
        child: Consumer<ThemeProvider>(builder: (context, themeProvider, child) {
          // MaterialApp sebagai root aplikasi
          return MaterialApp(
            navigatorKey: navigatorKey, // Untuk navigasi global
            builder: (context, widget) => ResponsiveBreakpoints.builder(
              child: ClampingScrollWrapper.builder(context, widget!),
              breakpoints: [
                const Breakpoint(start: 0, end: 450, name: MOBILE),
                const Breakpoint(start: 451, end: 800, name: TABLET),
                const Breakpoint(start: 801, end: 1920, name: DESKTOP),
                const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
              ],
            ),
            debugShowCheckedModeBanner: false,
            title: 'Vocasia',
            theme: themeProvider.themeData, // Tema aplikasi
            home: const SplashScreenLogin(), // Halaman pertama (Splash)
            routes: routes, // Daftar route aplikasi
          );
        }),
      ),
    );
  }
}
