import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:localization/localization.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/comments_provider.dart';
import 'package:test_sa/controllers/providers/api/departments_provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_provider.dart';
import 'package:test_sa/controllers/providers/api/devices_provider.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_provider.dart';
import 'package:test_sa/controllers/providers/api/hospitals_provider.dart';
import 'package:test_sa/controllers/providers/api/notifications_provider.dart';
import 'package:test_sa/controllers/providers/api/parts_provider.dart';
import 'package:test_sa/controllers/providers/api/ppm_provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_assistants_employee_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_fault_description_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_last_calls_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_repair_location_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_types_provider.dart';
import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/modules/cm_module/views/nurse/create_new_request_view.dart';
import 'package:test_sa/modules/tm_module/tasks_wo/create_task_view.dart';
import 'package:test_sa/new_views/app_style/app_themes.dart';
import 'package:test_sa/new_views/pages/help_center_page.dart';
import 'package:test_sa/new_views/pages/land_page/land_page.dart';
import 'package:test_sa/new_views/pages/login_page.dart';
import 'package:test_sa/new_views/pages/report_bug_page.dart';
import 'package:test_sa/new_views/pages/settings_page.dart';
import 'package:test_sa/new_views/pages/splash_page.dart';
import 'package:test_sa/new_views/pages/unsafe_device_view.dart';
import 'package:test_sa/new_views/swipe_module/swipe_history_view.dart';
import 'package:test_sa/new_views/swipe_module/swipe_success_view.dart';
import 'package:test_sa/new_views/swipe_module/swipe_view.dart';
import 'package:test_sa/providers/asset_transfer/asset_transfer_status_provider.dart';
import 'package:test_sa/providers/department_provider.dart';
import 'package:test_sa/providers/gas_request_providers/cylinder_size_provider.dart';
import 'package:test_sa/providers/gas_request_providers/cylinder_type_provider.dart';
import 'package:test_sa/providers/gas_request_providers/gas_status_provider.dart';
import 'package:test_sa/providers/gas_request_providers/gas_types_provider.dart';
import 'package:test_sa/providers/gas_request_providers/site_provider.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/ppm_asset_availability_provider.dart';
import 'package:test_sa/providers/ppm_checklist_status_provider.dart';
import 'package:test_sa/providers/ppm_device_status_provider.dart';
import 'package:test_sa/providers/ppm_electrical_safety_provider.dart';
import 'package:test_sa/providers/ppm_service_provider.dart';
import 'package:test_sa/providers/ppm_task_status_provider.dart';
import 'package:test_sa/providers/ppm_visit_status_provider.dart';
import 'package:test_sa/providers/service_request_providers/commissioning_status_provider.dart';
import 'package:test_sa/providers/service_request_providers/equipment_status_provider.dart';
import 'package:test_sa/providers/service_request_providers/first_action_provider.dart';
import 'package:test_sa/providers/service_request_providers/last_situation_provider.dart';
import 'package:test_sa/providers/service_request_providers/priority_provider.dart';
import 'package:test_sa/providers/service_request_providers/requested_through_provider.dart';
import 'package:test_sa/providers/service_request_providers/type_of_request_provider.dart';
import 'package:test_sa/providers/task_request_provider/task_job_provider.dart';
import 'package:test_sa/providers/task_request_provider/task_request_provider.dart';
import 'package:test_sa/providers/work_order/activity_status_provider.dart';
import 'package:test_sa/providers/work_order/fault_description_provider.dart';
import 'package:test_sa/providers/work_order/need_visit_reminder_time_provider.dart';
import 'package:test_sa/providers/work_order/reason_provider.dart';
import 'package:test_sa/providers/work_order/retirement_type_provider.dart';
import 'package:test_sa/providers/work_order/service_type_provider.dart';
import 'package:test_sa/providers/work_order/supplier_engineer_provider.dart';
import 'package:test_sa/providers/work_order/vendor_provider.dart';
import 'package:test_sa/providers/work_order/wo_frame_provider.dart';
import 'package:test_sa/views/pages/device_transfer/create__device_transfer_request.dart';
import 'package:test_sa/views/pages/device_transfer/device_filter_screen.dart';
import 'package:test_sa/views/pages/device_transfer/device_search_screen.dart';
import 'package:test_sa/views/pages/user/gas_refill/request_gas_refill.dart';
import 'package:test_sa/views/pages/user/gas_refill/update_gas_refill_request.dart';
import 'package:test_sa/views/pages/user/notifications/notifications_page.dart';
import 'package:test_sa/views/pages/user/profile_page.dart';
import 'package:test_sa/views/pages/user/requests/create_service_request_page.dart';
import 'package:test_sa/views/update_available_screen.dart';
import 'package:test_sa/views/widgets/departments/single_department_picker.dart';
import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart';
import 'package:test_sa/views/widgets/equipment/single_device_picker.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

import 'controllers/notification/notification_manger.dart';
import 'controllers/providers/api/gas_refill_comments.dart';
import 'controllers/providers/api/user_provider.dart';
import 'controllers/providers/settings/setting_provider.dart';
import 'dashboard_latest/dashboard_provider.dart';
import 'new_views/pages/gas_refill_request_form.dart';
import 'providers/service_request_providers/loan_availability_provider.dart';
import 'providers/service_request_providers/reject_reason_provider.dart';

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // HttpOverrides.global = MyHttpOverrides(); // for later use.
  _configureLocalTimeZone();
  NotificationManger.initialisation((notificationDetails) {}, (id, title, body, payload) async {});

  if (Platform.isIOS) {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "AIzaSyACQkSleNwU1jzEKR5ho1uSfZERokwwAbc",
        appId: "1:973582662416:ios:bc4a8061444c6a08fbc395",
        messagingSenderId: "973582662416",
        projectId: "atoms-fb912",
      ),
    );
  } else {
    await Firebase.initializeApp();
  }
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.white));

  /// only portrait mode
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(ChangeNotifierProvider(create: (_) => SettingProvider(), child: const MyApp()));
}

//this function is used for schedule notifications
Future<void> _configureLocalTimeZone() async {
  try {
    if (kIsWeb || Platform.isLinux) {
      return;
    }
    tz.initializeTimeZones();
    final String timeZoneName = await FlutterTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(timeZoneName));
  } catch (e) {
    return;
  }
}

final navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    LocalJsonLocalization.delegate.directories = ['assets/translations'];
    final settingProvider = Provider.of<SettingProvider>(context);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
        ChangeNotifierProvider(create: (_) => GasTypesProvider()),
        ChangeNotifierProvider(create: (_) => NullableLoadingProvider()),
        ChangeNotifierProvider(create: (_) => CylinderTypesProvider()),
        ChangeNotifierProvider(create: (_) => CylinderSizeProvider()),
        ChangeNotifierProvider(create: (_) => DepartmentProvider()),
        ChangeNotifierProvider(create: (_) => SiteProvider()),
        ChangeNotifierProvider(create: (_) => MappedSiteProvider()),
        ChangeNotifierProvider(create: (_) => NurseProvider()),
        ChangeNotifierProvider(create: (_) => HospitalsProvider()),
        ChangeNotifierProvider(create: (_) => AssetProvider()),
        ChangeNotifierProvider(create: (_) => AllRequestsProvider()),
        ChangeNotifierProvider(create: (_) => ServiceRequestsProvider()),
        ChangeNotifierProvider(create: (_) => DepartmentsProvider()),
        ChangeNotifierProvider(create: (_) => NotificationsProvider()),
        //new providers according to new Api's..
        ChangeNotifierProvider(create: (_) => DashBoardProvider()),
        ChangeNotifierProvider(create: (_) => ServiceRequestDetailProvider()),
        // ChangeNotifierProvider(create: (_) => PreventiveMaintenanceVisitsProvider()),
        ChangeNotifierProvider(create: (_) => PpmProvider()),
        ChangeNotifierProvider(create: (_) => PartsProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceReportReasonsProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceReportStatusProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceReportEquipmentStatusProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceReportTypesProvider()),
        ChangeNotifierProvider(create: (_) => ServiceStatusProvider()),
        ChangeNotifierProvider(create: (_) => ServiceReportLastCallsProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => GasCylinderSizesProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => GasCylinderTypesProvider()),
        ChangeNotifierProvider(create: (_) => GasStatusProvider()),
        ChangeNotifierProvider(create: (_) => GasTypesProvider()),
        ChangeNotifierProvider(create: (_) => GasRefillProvider()),
        ChangeNotifierProvider(create: (_) => DeviceTransferProvider()),
        ChangeNotifierProvider(create: (_) => AssetTransferStatusProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => AssignedToProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => PentryTaskStatusProvider()),
        //ChangeNotifierProvider(create: (_) => PentryVisitStatusProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => PentryStatusProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceRequestPriorityProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceRequestDefectTypesProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceRequestTypeProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceRequestedThroughProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceRequestStatusProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => EngineersProvider()),
        ChangeNotifierProvider(create: (_) => SupplierEngineerProvider()),

        /// Loan availability not required
        // ChangeNotifierProvider(create: (_) => ServiceLoanAvailabilityProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceFirstActionProvider()),
        ChangeNotifierProvider(create: (_) => ServiceReportRepairLocationProvider()),
        ChangeNotifierProvider(create: (_) => ServiceRequestFaultDescriptionProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceReportVisitOperatorProvider()),
        ///todo deleted
        //ChangeNotifierProvider(create: (_) => ServiceReportMaintenanceSituationProvider()),
        //ChangeNotifierProvider(create: (_) => ServiceReportUsersProvider()),
        ChangeNotifierProvider(create: (_) => ServiceReportAssistantsEmployeeProvider()),
        ChangeNotifierProvider(create: (_) => PriorityProvider()),
        ChangeNotifierProvider(create: (_) => EquipmentStatusProvider()),
        ChangeNotifierProvider(create: (_) => CommissioningStatusProvider()),
        ChangeNotifierProvider(create: (_) => RequestedThroughProvider()),
        ChangeNotifierProvider(create: (_) => TypeOfRequestProvider()),
        ChangeNotifierProvider(create: (_) => FirstActionStatusProvider()),

        /// Loan availability not required
        ChangeNotifierProvider(create: (_) => LoanAvailabilityProvider()),
        ChangeNotifierProvider(create: (_) => ReasonProvider()),
        ChangeNotifierProvider(create: (_) => WoFrameProvider()),
        ChangeNotifierProvider(create: (_) => RejectReasonProvider()),
        ChangeNotifierProvider(create: (_) => LastSituationProvider()),
        ChangeNotifierProvider(create: (_) => FaultDescriptionProvider()),
        ChangeNotifierProvider(create: (_) => RetirementTypeProvider()),
        ChangeNotifierProvider(create: (_) => ActivityStatusProvider()),
        ChangeNotifierProvider(create: (_) => NeedVisitReminderTimeProvider()),

        //task request providers.
        ChangeNotifierProvider(create: (_) => TaskRequestProvider()),
        ChangeNotifierProvider(create: (_) => TaskTypeProvider()),
        ChangeNotifierProvider(create: (_) => TaskJobTypeOfAlertProvider()),
        ChangeNotifierProvider(create: (_) => TaskJobRiskLevelProvider()),
        ChangeNotifierProvider(create: (_) => TaskJobResourceProvider()),
        ChangeNotifierProvider(create: (_) => TaskJobActionNeededProvider()),
        ChangeNotifierProvider(create: (_) => TaskEvaluatorUserProvider()),
        ChangeNotifierProvider(create: (_) => TaskJobImpactStatusProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => AssetTypesProvider()),
        ChangeNotifierProvider(create: (_) => ServiceTypeProvider()),
        ChangeNotifierProvider(create: (_) => PPMVisitStatusProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => PentryTaskStatusProvider()),
        ChangeNotifierProvider(create: (_) => PPMDeviceStatusProvider()),
        ChangeNotifierProvider(create: (_) => PpmAssetAvailabilityProvider()),
        ChangeNotifierProvider(create: (_) => PpmTaskStatusProvider()),
        ChangeNotifierProvider(create: (_) => PpmElectricalSafetyProvider()),
        ChangeNotifierProvider(create: (_) => PpmServiceProvider()),
        ChangeNotifierProvider(create: (_) => CommentsProvider()),
        ChangeNotifierProvider(create: (_) => GasRefillCommentsProvider()),

        ///todo deleted
        //ChangeNotifierProvider(create: (_) => RequestStatusProvider()),
        ChangeNotifierProvider(create: (_) => VendorProvider()),
        ChangeNotifierProvider(create: (_) => PpmChecklistStatusProvider()),
      ],
      child: GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus) {
            FocusManager.instance.primaryFocus!.unfocus();
          }
        },
        child: MaterialApp(
          title: 'ATOMS',
          debugShowCheckedModeBanner: false,
          theme: settingProvider.theme == "dark" ? AppThemes.darkTheme : AppThemes.lightTheme,
          localizationsDelegates: AppLocalizations.localizationsDelegates,
          supportedLocales: AppLocalizations.supportedLocales,
          locale: Locale(settingProvider.language ?? 'en'),
          initialRoute: SplashPage.routeName,
          navigatorKey: navigatorKey,
          routes: {
            SplashPage.routeName: (_) => const SplashPage(),
            LoginPage.routeName: (_) => const LoginPage(),
            UnsafeDeviceScreen.routeName: (_) => const UnsafeDeviceScreen(),
            SwipeSuccessView.routeName: (_) => const SwipeSuccessView(),
            SwipeHistoryView.routeName: (_) => const SwipeHistoryView(),
            SwipeView.routeName: (_) => const SwipeView(),
            UpdateAvailableScreen.routeName: (_) => UpdateAvailableScreen(),

            ///todo deleted
            //old.LandPage.id: (_) => const old.LandPage(),
            LandPage.routeName: (_) => const LandPage(),
            GasRefillRequestForm.routeName: (_) => const GasRefillRequestForm(),
            // ServiceRequestsPage.id: (_) => const ServiceRequestsPage(),
            CreateTaskView.id: (_) => const CreateTaskView(),
            //ReportIssuesPage.id: (_) =>  ReportIssuesPage(),
            RequestGasRefill.id: (_) => const RequestGasRefill(),
            UpdateGasRefillRequest.id: (_) => const UpdateGasRefillRequest(),
            CreateServiceRequestPage.id: (_) => const CreateServiceRequestPage(),
            CreateNewRequest.id: (_) => const CreateNewRequest(),
            // SingleHospitalPicker.id: (_) => SingleHospitalPicker(),
            MyAssetsPage.id: (_) => const MyAssetsPage(),
            SingleDepartmentPicker.id: (_) => const SingleDepartmentPicker(),
            NotificationsPage.id: (_) => const NotificationsPage(),
            // FutureRequestServiceDetails.id: (_) => FutureRequestServiceDetails(),
            // PreventiveMaintenanceVisitsPage.id: (_) => PreventiveMaintenanceVisitsPage(),
            // PpmPage.id: (_) => const PpmPage(),
            // TrackGasRefillPage.id: (_) => const TrackGasRefillPage(),
            CreateDeviceTransferRequest.id: (_) => const CreateDeviceTransferRequest(),
            // TrackDeviceTransferPage.id: (_) => const TrackDeviceTransferPage(),

            // SearchSubWorkOrderPage.id: (_) => const SearchSubWorkOrderPage(),
            // CreateSubWorkOrderPage.id: (_) => const CreateSubWorkOrderPage(),
            // WorkOrderListPage.id: (_) => WorkOrderListPage(),
            AssetDetailPage.id: (_) => const AssetDetailPage(),
            DeviceSearchScreen.id: (_) => const DeviceSearchScreen(),
            DeviceFilterScreen.id: (_) => const DeviceFilterScreen(),
            // WorkOrderDetailsPage.id: (_) => const WorkOrderDetailsPage(),
            // UpdateServiceRequestPage.id: (_) => const UpdateServiceRequestPage(),

            SettingsPage.id: (_) => const SettingsPage(),
            ProfilePage.id: (_) => const ProfilePage(),
            ReportBugPage.id: (_) => const ReportBugPage(),
            HelpCenterPage.id: (_) => const HelpCenterPage(),
            // SwipeSuccessView.routeName: (_) => const SwipeSuccessView(),
            // SwipeHistoryView.routeName: (_) => const SwipeHistoryView(),
          },
        ),
      ),
    );
  }
}
