// ignore_for_file: avoid_print

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_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/core/services/ad/cubit/on_show_add_cubit.dart';
import 'package:hoshan/core/services/ad/tapsell_service.dart';
import 'package:hoshan/core/services/firebase/firebase_api.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/firebase_options.dart';
import 'package:hoshan/ui/screens/cmp/cubit/cmp_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/medias_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/single_media_cubit.dart';
import 'package:hoshan/ui/screens/main/assistant/bloc/global_assistants_bloc.dart';
import 'package:hoshan/ui/screens/main/assistant/bloc/personal_assistants_bloc.dart';
import 'package:hoshan/ui/screens/main/home/bloc/bots_bloc.dart';
import 'package:hoshan/ui/screens/main/home/bloc/cubit/posts_cubit.dart';
import 'package:hoshan/ui/screens/main/forum/cubit/category_cubit.dart';
import 'package:hoshan/ui/screens/library/bloc/chats_history_bloc.dart';
import 'package:hoshan/ui/screens/main/home/cubit/main_chat_bot_cubit.dart';
import 'package:hoshan/ui/screens/main/persons/cubit/persons_cubit.dart';
import 'package:hoshan/ui/screens/setting/bloc/paymant_history_bloc.dart';
import 'package:hoshan/ui/screens/setting/cubit/ad_remaining_cubit.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/screens/tools/bloc/tools_bloc.dart';
import 'package:hoshan/ui/theme/cubit/theme_mode_cubit.dart';
import 'package:hoshan/ui/theme/my_custom_scroll_behavior.dart';
import 'package:hoshan/ui/theme/theme.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:url_strategy/url_strategy.dart';

@pragma('vm:entry-point')
Future<void> _onBackgroundMessage(RemoteMessage message) async {
  debugPrint("Handling a background message: ${message.messageId}");
}

void main() async {
  setPathUrlStrategy();
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await SharedPreferencesHelper.initial();
  } catch (e) {
    debugPrint("Error initializing SharedPreferences: $e");
  }

  try {
    await TapsellService.initialize();
  } catch (e) {
    debugPrint("Error initializing Tapsell: $e");
  }

  print('🚀 Starting Firebase Initialization...');
  try {
    FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage);

    FirebaseOptions options = DefaultFirebaseOptions.currentPlatform;

    if (defaultTargetPlatform == TargetPlatform.android) {
       print('🤖 Platform is Android, checking package info...');
       final packageInfo = await PackageInfo.fromPlatform();
       print("📦 RUNNING WITH PACKAGE: ${packageInfo.packageName}");
       
       if (packageInfo.packageName == 'com.houshan.basa') {
         options = DefaultFirebaseOptions.androidHoushan;
         print("🔥 Using 'androidHoushan' options (Basa)");
       } else if (packageInfo.packageName == 'com.houshan.hoshan') {
         options = DefaultFirebaseOptions.androidHoushanMain;
         print("🔥 Using 'androidHoushanMain' options (Main)");
       } else {
         print("⚠️ Unknown package name, using default options");
       }
    }

    if (Firebase.apps.isEmpty) {
      print('⏳ Calling Firebase.initializeApp...');
      try {
        await Firebase.initializeApp(options: options);
        print('✅ Firebase.initializeApp completed.');
      } catch (e) {
         print('⚠️ Firebase.initializeApp failed: $e');
         if (e.toString().contains('duplicate-app')) {
             print('ℹ️ Ignoring duplicate-app error and continuing...');
         } else {
             rethrow;
         }
      }
    } else {
      print('ℹ️ Firebase already initialized. Skipping initialization.');
    }
    
    print('⏳ Calling FirebasApi.initialNotifications()...');
    await FirebasApi.initialNotifications();
  } catch (e, stack) {
    print('❌❌ Error initializing Firebase: $e');
    print(stack);
  }

  try {
    if (!kIsWeb) {
      await FlutterDownloader.initialize(debug: true, ignoreSsl: true);
      print('✅ FlutterDownloader initialized');
    }
  } catch (e) {
    debugPrint('Error initializing FlutterDownloader: $e');
  }

  // Run App
  print('✅✅ Main initialization completed! Starting app...');
  if (kReleaseMode) {
    await SentryFlutter.init((options) {
      options.dsn =
          'https://9bb2d441e4aa30034c88783673cd64a4@o4508585857384448.ingest.de.sentry.io/4509043371212880';

      options.sendDefaultPii = true;
    },
        appRunner: () => runApp(mainApp()));
  } else {
    runApp(mainApp());
  }
  print('🚀🚀 App started successfully!');
}

MultiBlocProvider mainApp() {
  return MultiBlocProvider(
    providers: [
      BlocProvider<BotsBloc>(
        create: (context) => BotsBloc()..add(GetAllBots()),
      ),
      BlocProvider<ThemeModeCubit>(
        create: (context) => ThemeModeCubit(),
      ),
      BlocProvider<CategoryCubit>(
        create: (context) => CategoryCubit()..getAllCategorie(),
      ),
      BlocProvider<UserInfoCubit>(
        create: (context) => UserInfoCubit(),
      ),
      BlocProvider<ChatsHistoryBloc>(
        create: (context) => ChatsHistoryBloc(),
      ),
      BlocProvider<PaymantHistoryBloc>(
        create: (context) => PaymantHistoryBloc()..add(GetAllHistory()),
      ),
      BlocProvider<ToolsBloc>(
        create: (context) => ToolsBloc()..add(GetAllTools()),
      ),
      BlocProvider<PersonalAssistantsBloc>(
        create: (context) => PersonalAssistantsBloc()..add(GetAll()),
      ),
      BlocProvider<GlobalAssistantsBloc>(
        create: (context) =>
            GlobalAssistantsBloc()..add(const GetGlobalAssistants()),
      ),
      BlocProvider<PersonsCubit>(
        create: (context) => PersonsCubit()..getCharacters(),
      ),
      BlocProvider<PostsCubit>(
        create: (context) => PostsCubit()..getLastPosts(),
      ),
      BlocProvider<CmpCubit>(
        create: (context) => CmpCubit()..getAllEvents(),
      ),
      BlocProvider<MediasCubit>(
        create: (context) => MediasCubit()..getMedias(),
      ),
      BlocProvider<SingleMediaCubit>(
        create: (context) => SingleMediaCubit(),
      ),
      BlocProvider<MainChatBotCubit>(
        create: (context) => MainChatBotCubit()..getBot(1),
      ),
      BlocProvider<OnShowAddCubit>(
        create: (context) => OnShowAddCubit(),
      ),
      BlocProvider<AdRemainingCubit>(
        create: (context) => AdRemainingCubit()..getRemainingAd(),
      )
    ],
    child: const MyApp(),
  );
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

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

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ThemeModeCubit, ThemeMode>(
      builder: (context, state) {
        final isDark = state == ThemeMode.dark;
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
          systemNavigationBarContrastEnforced: false,

          systemNavigationBarColor: isDark
              ? darkThemeDefault.scaffoldBackgroundColor
              : lightDefaultTheme
                  .scaffoldBackgroundColor, // Change the bottom navigation bar color
          systemNavigationBarIconBrightness: isDark
              ? Brightness.light
              : Brightness.dark, // Change icon color (light/dark)
        ));
        return Container(
          color: isDark
              ? darkThemeDefault.scaffoldBackgroundColor
              : lightDefaultTheme.scaffoldBackgroundColor,
          child: Padding(
            padding:
                EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
            child: Material(
              child: MaterialApp.router(
                title: 'هوشان',
                debugShowCheckedModeBanner: false,
                // initialRoute: Routes.main,
                // navigatorKey: navigatorKey,
                // onGenerateRoute: Routes.router,
                routerConfig: Routes.routeGenerator,
                scrollBehavior: MyCustomScrollBehavior(),
                themeMode: state,
                theme: isDark ? darkThemeDefault : lightDefaultTheme,
              ),
            ).animate().fadeIn(duration: 400.ms),
          ),
        );
      },
    );
  }
}
