import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.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:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/active_prescriptions/active_prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/blood_donation/blood_donation_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart';
import 'package:hmg_patient_app_new/features/doctor_filter/doctor_filter_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/features/health_trackers/health_trackers_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/features/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/features/lab/history/lab_history_viewmodel.dart';
import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/features/location/location_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/features/monthly_report/monthly_report_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/appointment_rating_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/my_invoices/my_invoices_view_model.dart';
import 'package:hmg_patient_app_new/features/notifications/notifications_view_model.dart';
import 'package:hmg_patient_app_new/features/offers_and_discounts/offers_and_discounts_view_model.dart';
import 'package:hmg_patient_app_new/features/payfort/payfort_view_model.dart';
import 'package:hmg_patient_app_new/features/paytabs/paytabs_view_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/features/profile_picture/profile_picture_view_model.dart';
import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart';
import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_view_model.dart';
import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart';
import 'package:hmg_patient_app_new/features/refund_request/refund_request_view_model.dart';
import 'package:hmg_patient_app_new/features/services_price_list/services_price_list_view_model.dart';
import 'package:hmg_patient_app_new/features/smartwatch_health_data/health_provider.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart';
import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart';
import 'package:hmg_patient_app_new/features/weather/weather_view_model.dart';
import 'package:hmg_patient_app_new/presentation/health_calculators_and_converts/health_calculator_view_model.dart';
import 'package:hmg_patient_app_new/routes/app_routes.dart';
import 'package:hmg_patient_app_new/services/app_lifecycle_service.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/theme/app_theme.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_calendar_model.dart';
import 'package:hmg_patient_app_new/widgets/date_range_selector/viewmodel/date_range_view_model.dart' show DateRangeSelectorRangeViewModel;
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';

import 'core/utils/size_utils.dart';
import 'features/monthly_reports/terms_conditions_view_model.dart';
import 'firebase_options.dart';


@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  getIt.get<LoggerService>().logInfo("Firebase backgroundMessageHandler Main!!!");
}

// flutter3_32 pub run easy_localization:generate -O ./lib/generated -f keys -o locale_keys.g.dart --source-dir ./assets/langs

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  }
}

Future<void> callAppStateInitializations() async {
  final String deviceTypeId = (Platform.isIOS
      ? "1"
      : await Utils.isGoogleServicesAvailable()
          ? "2"
          : "3");
  AppState appState = getIt.get<AppState>();
  appState.setDeviceTypeID = deviceTypeId;

  // Pass all uncaught "fatal" errors from the framework to Crashlytics
  if (!kDebugMode) {
    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
  }

  // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
  PlatformDispatcher.instance.onError = (error, stack) {
    if (!kDebugMode) {
      FirebaseCrashlytics.instance.recordError(error, stack,
          fatal: false,
          printDetails: true,
          reason:
              "${appState.isAuthenticated ? "Authenticated User ID: ${appState.getAuthenticatedUser()!.patientId} - ${appState.getAuthenticatedUser()!.mobileNumber}" : "Unauthenticated User"} - Uncaught asynchronous error");
    }
    return true;
  };
}

Future<void> callInitializations() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  try {
    // Attempt to get the default app. If it exists, this avoids the error.
    await Firebase.app();
  } catch (e) {
    // If it doesn't exist, initialize it.
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
  }

  await AppDependencies.addDependencies();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  HttpOverrides.global = MyHttpOverrides();
  await callAppStateInitializations();

  // Initialize App Lifecycle Service to monitor background/foreground transitions
  getIt.get<AppLifecycleService>().initialize();

  // Restore persisted dark-mode preference before the first frame.
  getIt.get<ProfileSettingsViewModel>().loadDarkMode();

  // Restore persisted accessibility settings before the first frame.
  getIt.get<ProfileSettingsViewModel>().loadAccessibilitySettings();
}

void main() async {
  await callInitializations();
  runApp(
    EasyLocalization(
      supportedLocales: const <Locale>[
        Locale('en', 'US'),
        Locale('ar', 'SA'),
      ],
      path: 'assets/langs',
      // assetLoader: RemoteFileLoader(),
      fallbackLocale: Locale('en', 'US'),
      child: MultiProvider(providers: <SingleChildWidget>[
        ChangeNotifierProvider<LabViewModel>(
          create: (_) => getIt.get<LabViewModel>(),
        ),
        ChangeNotifierProvider<RadiologyViewModel>(
          create: (_) => getIt.get<RadiologyViewModel>(),
        ),
        ChangeNotifierProvider<PrescriptionsViewModel>(
          create: (_) => getIt.get<PrescriptionsViewModel>(),
        ),
        ChangeNotifierProvider<InsuranceViewModel>(
          create: (_) => getIt.get<InsuranceViewModel>(),
        ),
        ChangeNotifierProvider<MedicalFileViewModel>(
          create: (_) => getIt.get<MedicalFileViewModel>(),
        ),
        ChangeNotifierProvider<ProfileSettingsViewModel>(
          create: (_) => getIt.get<ProfileSettingsViewModel>(),
        ),
        ChangeNotifierProvider<ProfilePictureViewModel>(
          create: (_) => getIt.get<ProfilePictureViewModel>(),
        ),
        ChangeNotifierProvider<MyAppointmentsViewModel>(
          create: (_) => getIt.get<MyAppointmentsViewModel>(),
        ),
        ChangeNotifierProvider<AppointmentRatingViewModel>(
          create: (_) => getIt.get<AppointmentRatingViewModel>(),
        ),
        ChangeNotifierProvider<PayfortViewModel>(
          create: (_) => getIt.get<PayfortViewModel>(),
        ),
        ChangeNotifierProvider<HabibWalletViewModel>(
          create: (_) => getIt.get<HabibWalletViewModel>(),
        ),
        ChangeNotifierProvider<BookAppointmentsViewModel>(
          create: (_) => getIt.get<BookAppointmentsViewModel>(),
        ),
        ChangeNotifierProvider<ImmediateLiveCareViewModel>(
          create: (_) => getIt.get<ImmediateLiveCareViewModel>(),
        ),
        ChangeNotifierProvider<AuthenticationViewModel>(
          create: (_) => getIt.get<AuthenticationViewModel>(),
        ),
        ChangeNotifierProvider<AppointmentViaRegionViewmodel>(
          create: (_) => getIt.get<AppointmentViaRegionViewmodel>(),
        ),
        ChangeNotifierProvider<LabHistoryViewModel>(
          create: (_) => getIt.get<LabHistoryViewModel>(),
        ),
        ChangeNotifierProvider<DateRangeSelectorRangeViewModel>(
          create: (_) => getIt.get<DateRangeSelectorRangeViewModel>(),
        ),
        ChangeNotifierProvider<DoctorFilterViewModel>(
          create: (_) => getIt.get<DoctorFilterViewModel>(),
        ),
        ChangeNotifierProvider<EmergencyServicesViewModel>(
          create: (_) => getIt.get<EmergencyServicesViewModel>(),
        ),
        ChangeNotifierProvider<LocationViewModel>(
          create: (_) => getIt.get<LocationViewModel>(),
        ),
        ChangeNotifierProvider<TodoSectionViewModel>(
          create: (_) => getIt.get<TodoSectionViewModel>(),
        ),
        ChangeNotifierProvider<ContactUsViewModel>(
          create: (_) => getIt.get<ContactUsViewModel>(),
        ),
        ChangeNotifierProvider<HmgServicesViewModel>(
          create: (_) => getIt.get<HmgServicesViewModel>(),
        ),
        ChangeNotifierProvider<SymptomsCheckerViewModel>(
          create: (_) => getIt.get<SymptomsCheckerViewModel>(),
        ),
        ChangeNotifierProvider<BloodDonationViewModel>(
          create: (_) => getIt.get<BloodDonationViewModel>(),
        ),
        ChangeNotifierProvider<HealthProvider>(
          create: (_) => getIt.get<HealthProvider>(),
        ),
        ChangeNotifierProvider<HealthCalcualtorViewModel>(
          create: (_) => getIt.get<HealthCalcualtorViewModel>(),
        ),
        ChangeNotifierProvider<WaterMonitorViewModel>(
          create: (_) => getIt.get<WaterMonitorViewModel>(),
        ),
        ChangeNotifierProvider<MyInvoicesViewModel>(
          create: (_) => getIt.get<MyInvoicesViewModel>(),
        ),
        ChangeNotifierProvider<HealthTrackersViewModel>(
          create: (_) => getIt.get<HealthTrackersViewModel>(),
        ),
        ChangeNotifierProvider<MonthlyReportViewModel>(
          create: (_) => getIt.get<MonthlyReportViewModel>(),
        ),
        ChangeNotifierProvider<NotificationsViewModel>(
          create: (_) => getIt.get<NotificationsViewModel>(),
        ),
        ChangeNotifierProvider<ActivePrescriptionsViewModel>(
          create: (_) => getIt.get<ActivePrescriptionsViewModel>(),
        ),
        ChangeNotifierProvider<QrParkingViewModel>(
          create: (_) => getIt.get<QrParkingViewModel>(),
        ),
        ChangeNotifierProvider<TermsConditionsViewModel>(
          create: (_) => getIt.get<TermsConditionsViewModel>(),
        ),
        ChangeNotifierProvider<AskDoctorViewModel>(
          create: (_) => getIt.get<AskDoctorViewModel>(),
        ),
        ChangeNotifierProvider<ServicesPriceListViewModel>(
          create: (_) => getIt.get<ServicesPriceListViewModel>(),
        ),
        ChangeNotifierProvider<OffersAndDiscountsViewModel>(
          create: (_) => getIt.get<OffersAndDiscountsViewModel>(),
        ),
        ChangeNotifierProvider<WeatherMonitorViewModel>(
          create: (_) => getIt.get<WeatherMonitorViewModel>(),
        ),
        ChangeNotifierProvider<DateRangCalenderModel>(
          create: (_) => getIt.get<DateRangCalenderModel>(),
        ),
        ChangeNotifierProvider<PayTabsViewModel>(
          create: (_) => getIt.get<PayTabsViewModel>(),
        ),
        ChangeNotifierProvider<RefundRequestViewModel>(
          create: (_) => getIt.get<RefundRequestViewModel>(),
        )
      ], child: MyApp()),
    ), // Wrap your app
  );
}

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

  /// Apply visual mode filter to the entire app
  Widget _applyVisualMode(String visualMode, Widget child) {
    switch (visualMode) {
      case 'invert':
        // Invert colors app-wide (red becomes cyan for colorblind users)
        return ColorFiltered(
          colorFilter: const ColorFilter.matrix(<double>[
            -1, 0, 0, 0, 255, // Red channel inverted
            0, -1, 0, 0, 255, // Green channel inverted
            0, 0, -1, 0, 255, // Blue channel inverted
            0, 0, 0, 1, 0, // Alpha channel unchanged
          ]),
          child: child,
        );

      case 'dim':
        // Apply dim effect with opacity overlay
        return Stack(
          children: [
            child,
            Positioned.fill(
              child: IgnorePointer(
                child: Container(
                  color: Colors.black.withValues(alpha: 0.3), // 30% black overlay for dimming
                ),
              ),
            ),
          ],
        );

      case 'highContrast':
        // Apply desaturation for high contrast (removes colors, leaves black and white)
        return ColorFiltered(
          colorFilter: const ColorFilter.matrix(<double>[
            0.2126, 0.7152, 0.0722, 0, 0, // Red channel (grayscale)
            0.2126, 0.7152, 0.0722, 0, 0, // Green channel (grayscale)
            0.2126, 0.7152, 0.0722, 0, 0, // Blue channel (grayscale)
            0, 0, 0, 1, 0, // Alpha channel unchanged
          ]),
          child: child,
        );

      case 'off':
      default:
        // No filter applied
        return child;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false, // Set to true if you want to avoid the notch area as well
      bottom: Platform.isIOS ? false : true,
      child: LayoutBuilder(
        builder: (context, constraints) {
          return Sizer(
            builder: (context, orientation, deviceType) {
              // SizeConfig().init(constraints, orientation);
              return Consumer<ProfileSettingsViewModel>(
                builder: (context, profileVm, _) {
                  final isArabic = EasyLocalization.of(context)?.locale.languageCode == "ar";
                  return MaterialApp(
                    key: ValueKey('app_theme_${profileVm.isDarkMode}'),
                    // title: 'Dr. AlHabib',
                    title: 'Dr. AlHabib Beta',
                    builder: (context, mchild) {
                      Widget child = MediaQuery(
                        data: MediaQuery.of(context).copyWith(
                          textScaler: TextScaler.linear(profileVm.getFontScaleMultiplier()),
                          alwaysUse24HourFormat: true,
                        ),
                        child: mchild!,
                      );

                      // Apply visual mode filters app-wide
                      return _applyVisualMode(profileVm.visualMode, child);
                    },
                    showSemanticsDebugger: false,
                    debugShowCheckedModeBanner: false,
                    localizationsDelegates: context.localizationDelegates,
                    supportedLocales: context.supportedLocales,
                    locale: context.locale,
                    initialRoute: AppRoutes.initialRoute,
                    routes: AppRoutes.routes,
                    theme: AppTheme.getTheme(isArabic),
                    darkTheme: AppTheme.getDarkTheme(isArabic),
                    themeMode: profileVm.isDarkMode ? ThemeMode.dark : ThemeMode.light,
                    navigatorKey: getIt.get<NavigationService>().navigatorKey,
                    navigatorObservers: [getIt.get<NavigationService>().routeObserver],
                  );
                },
              );
            },
          );
        },
      ),
    );
  }
}
// flutter pub run easy_localization:generate -S assets/langs -f keys -o locale_keys.g.dart
