import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_dotenv/flutter_dotenv.dart';
// import 'package:flutter_windowmanager/flutter_windowmanager.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:loader_overlay/loader_overlay.dart';
import 'package:responsive_framework/responsive_framework.dart';
import 'app/bindings/dependency_injections.dart';
import 'app/core/config/connectivity_service.dart';
import 'app/core/utils/root_detector_device.dart';
import 'app/core/utils/simulator_check.dart';
import 'app/custom_widgets/custom_toasty.dart';
import 'app/res/app_colors.dart';
import 'app/res/app_theme.dart';
import 'app/res/suppoted_languages.dart';
import 'app/routes/app_pages.dart';

void main() async {
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: AppColors.colorPrimary,
    ),
  );
  WidgetsFlutterBinding.ensureInitialized();
  // await dotenv.load();
  bool isRootedOrJailbroken = await isDeviceRootedOrJailbroken();
  bool isDeviceEmulator = await isEmulator();
  if (isRootedOrJailbroken || isDeviceEmulator) {
    /// Display an error message and exit the app
    String errorMessage = isDeviceEmulator ? "This app cannot run on emulators or simulators." : "Rooted or jailbroken device detected.";
    Toasty.error(errorMessage);
    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    return;
    // runApp(const RootedOrJailbrokenDeviceApp());
  } else {
    /// Retrieve and decrypt the URL
    // final encryption = UrlEncryption();
    // String encryptedUrl = UrlEncryption().encryptData('https://uco.mfsys.ca');
    // print('Encrypted URL: $encryptedUrl');
    //
    // String decryptedUrl = UrlEncryption().decryptData(encryptedUrl);
    // print('Decrypted URL: $decryptedUrl');

    // FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE);
    await Hive.initFlutter();
    runApp(const MyApp(apiKey: '',));
  }
}

class MyApp extends StatefulWidget {
  final String apiKey;
  const MyApp({Key? key, required this.apiKey}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  ThemeData themeData = ThemeData();
  ConnectivityHelper connectivityHelper = ConnectivityHelper();

  void changeTheme(ThemeMode themeMode) {
    setState(() {
      themeMode = themeMode;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    connectivityHelper.checkNetworkConnectivity();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarColor: AppColors.colorPrimary));

    return GlobalLoaderOverlay(
      useDefaultLoading: false,
      overlayColor: Colors.black.withOpacity(0.2),
      overlayWidgetBuilder: (progress) => const CircularProgressIndicator(),
      child: GestureDetector(
        onTap: () {
          SystemChannels.textInput.invokeMethod('TextInput.hide');
        },
        child: GetMaterialApp(
          theme: appTheme(),
          defaultTransition: Transition.rightToLeftWithFade,
          darkTheme: appTheme(),
          debugShowCheckedModeBanner: false,
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.routes,
          initialBinding: DependencysInjections(),
          locale: const Locale("en"),
          translations: SupportedLanguages(),
          fallbackLocale: const Locale('en', 'ar'),
          builder: (context, child) {
            return ResponsiveBreakpoints.builder(
              child: BouncingScrollWrapper.builder(context, child!),
              breakpoints: [
                const Breakpoint(start: 0, end: 229, name: "m1"),
                const Breakpoint(start: 230, end: 320, name: "m2"),
                const Breakpoint(start: 321, end: 480, name: "m3"),
                const Breakpoint(start: 481, end: 640, name: "m4"),
                const Breakpoint(start: 641, end: 960, name: "m5"),
                const Breakpoint(start: 961, end: 1024, name: "m6"),
                const Breakpoint(start: 1025, end: 1280, name: "m7"),
                const Breakpoint(start: 1281, end: 1300, name: "m8"),
              ],
            );
          },
        ),
      ),
    );
  }
}
