// ignore_for_file: unnecessary_null_comparison

import 'dart:convert';

import 'package:byod/bloc/address_user_bloc.dart';
import 'package:byod/bloc/category_selection.dart';
import 'package:byod/bloc/check_voucher.dart';
import 'package:byod/bloc/member_info.dart';
import 'package:byod/bloc/order_bloc.dart';
import 'package:byod/bloc/search_menu.dart';
import 'package:byod/helper/prefs.dart';
import 'package:byod/ui/splash.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:web_browser_detect/web_browser_detect.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'bloc/branch_exist.dart';
import 'bloc/branch_list.dart';
import 'bloc/fav_selected_bar.dart';
import 'bloc/feedback_option.dart';
import 'bloc/feedback_select.dart';
import 'bloc/filter_menu.dart';
import 'bloc/menu_selected_bar.dart';
import 'bloc/order_detail_variant.dart';
import 'bloc/order_variant_temporary.dart';
import 'bloc/order_variant_value.dart';
import 'bloc/search_active.dart';
import 'bloc/search_branch.dart';
import 'bloc/search_history.dart';
import 'bloc/view_bill.dart';
import 'package:flutter/services.dart' as bundle_root;

import 'bloc/voucher_list.dart';
import 'ui/webview/webview.dart';

late SharedPreferences prefs;
bool isExcelso = false;
bool isResponsive = false;
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
String defaultTitle = 'Ravintola - BYOD';
bool debug = false; // set true pada config.json jika ingin ada log print
String browserName = 'Wrong platform';
String browserVersion = '';

//** Version Build Number */
const int majorVersion = 1;
const int minorVersion = 2;
List<String> stringPath = [];
String routesToAccess = '/';
//** Version Build Number */

void main() async {
  final browser = Browser.detectOrNull();
  browserName = browser?.browser ?? 'Wrong platform';
  browserVersion = browser?.version ?? 'Wrong platform';
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  setPathUrlStrategy();
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences.getInstance().then((value) {
    prefs = value;
    configLoading();
    for (int d = 0; d < Uri.base.pathSegments.length; d++) {
      if (Uri.base.pathSegments[0] != 'byod-neo/') {
        stringPath.add(Uri.base.pathSegments[d]);
        if (d == Uri.base.pathSegments.length - 1) {
          routesToAccess += Uri.base.pathSegments[d];
        } else {
          routesToAccess += '${Uri.base.pathSegments[d]}/';
        }
      }
    }
    loadAssetConfig().then((title) {
      setTitleWeb(title);
      runApp(
        MyApp(
          title: title,
        ),
      );
    });
  });
}

//easy loading
void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = true
    ..dismissOnTap = false;
}

Future<String> loadAssetConfig() async {
  String title;

  try {
    String datas = await bundle_root.rootBundle.loadString('config.json');
    var jsoDecode = jsonDecode(datas);
    title = jsoDecode['title'].toString();
    isResponsive = jsoDecode['isResponsive'];
    debug = jsoDecode['debug'];
    if (title == null) {
      return defaultTitle;
    } else {
      return title;
    }
  } catch (e) {
    return defaultTitle;
  }
}

// ignore: must_be_immutable
class MyApp extends StatefulWidget {
  // String myUrl, branch, brand, tn, role, cashierName, toViewBill;
  String title;
  MyApp({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    //** UUID */
    // const uuidInit = Uuid();
    // var uuid = uuidInit.v4();
    //** UUID */

    //** Check Session ID */
    // String currentOrderId = getOrderId();
    // String orderId;
    // if (currentOrderId != '') {
    //   orderId = currentOrderId;
    // } else {
    //   orderId = uuid;
    // }
    //** Check Session ID */

    // String branchStrg = '';
    // String brandStrg = '';
    // String tnStrg = '';
    // String roleStrg = 'customer';
    // String toBill = '';
    // String cashierNameStrg = '';
    // String tokenUser = '';

    // Future<bool> getLocationStatus() async {
    //   LocationPermission? permission;
    //   permission = await _geolocatorPlatform.requestPermission();
    //   if (permission == LocationPermission.denied) {
    //     return false;
    //   }

    //   return true;
    // }

    return MultiBlocProvider(
      providers: [
        BlocProvider(create: (_) => OrdersBloc()),
        BlocProvider(create: (_) => BranchExist()),
        // BlocProvider(create: (_) => CategoryMenu()),
        BlocProvider(create: (_) => OrderVariantTemporaryBloc()),
        BlocProvider(create: (_) => OrderVariantValueBloc()),
        BlocProvider(create: (_) => OrderDetailVariant()),
        BlocProvider(create: (_) => SearchMenu()),
        BlocProvider(create: (_) => VoucherCheck()),
        BlocProvider(create: (_) => CategorySelection()),
        BlocProvider(create: (_) => MemberInfoBloc()),
        BlocProvider(create: (_) => ViewBillBloc()),
        BlocProvider(create: (_) => FeedBackOptionBloc()),
        BlocProvider(create: (_) => FeedbackSelect()),
        BlocProvider(create: (_) => FilterMenuBloc()),
        BlocProvider(create: (_) => VoucherListBloc()),
        BlocProvider(create: (_) => FavSelectedBar()),
        BlocProvider(create: (_) => MenuSelectedBar()),
        BlocProvider(create: (_) => SearchActive()),
        BlocProvider(create: (_) => SearchHistory()),
        BlocProvider(create: (_) => BranchList()),
        BlocProvider(create: (_) => SearchBranch()),
        BlocProvider(create: (_) => AddressUser()),
      ],
      child: MaterialApp(
        title: (widget.title == null) ? defaultTitle : widget.title,
        builder: EasyLoading.init(),
        debugShowCheckedModeBanner: false,

        initialRoute: routesToAccess,
        routes: {
          routesToAccess: (context) => Splash(
                pathSegmentString: stringPath,
                context: context,
              ),
        },

        // initialRoute: '/',
        // routes: {
        //   '/': (context) => WebViewMap(
        //         titleAppBar: 'Pilih Alamat',
        //         url:
        //             'https://fdr-dev.ravku.com/web/store_url/706400e0-fb59-4317-a73b-8ff76f32f929/',
        //       ),
        // },
        // onGenerateRoute: (routes) {
        //   return MaterialPageRoute(
        //     builder: (context) => Splash(
        //       pathSegmentString: stringPath,
        //       context: context,
        //     ),
        //   );
        // },
        // onGenerateRoute: (routes) {
        //   var uri = Uri.parse(routes.name!);
        //   if (uri.pathSegments.isEmpty) {
        //     return MaterialPageRoute(
        //       builder: (context) => NoRoute(
        //         identification: 'emptyUri',
        //       ),
        //     );
        //   } else if (uri.pathSegments.length == 2) {
        //     setIsDeliveryPickup(false);
        //     String firstPath = uri.pathSegments.first;
        //     if (firstPath == 'o') {
        //       setTableMode(openBill);
        //       String orderIdPath = uri.pathSegments[1];
        //       return MaterialPageRoute(
        //         builder: (_) => Splash(
        //           branch: branchStrg,
        //           brand: brandStrg,
        //           tn: tnStrg,
        //           role: roleStrg,
        //           cashierName: cashierNameStrg,
        //           toBill: toBill,
        //           orderId: orderIdPath,
        //           token: tokenUser,
        //         ),
        //       );
        //       // do some api request for orderId
        //     }

        //     return MaterialPageRoute(
        //       builder: (_) => Splash(
        //         branch: branchStrg,
        //         brand: brandStrg,
        //         tn: tnStrg,
        //         role: roleStrg,
        //         cashierName: cashierNameStrg,
        //         toBill: toBill,
        //         orderId: orderId,
        //         token: tokenUser,
        //       ),
        //     );
        //   } else if (uri.pathSegments.length == 3) {
        //     setIsDeliveryPickup(false);
        //     brandStrg = uri.pathSegments.first;
        //     branchStrg = uri.pathSegments[1];
        //     tnStrg = uri.pathSegments[2];

        //     return MaterialPageRoute(
        //       builder: (_) => Splash(
        //         branch: branchStrg,
        //         brand: brandStrg,
        //         tn: tnStrg,
        //         role: roleStrg,
        //         cashierName: cashierNameStrg,
        //         toBill: toBill,
        //         orderId: orderId,
        //         token: tokenUser,
        //       ),
        //     );
        //   } else if (uri.pathSegments.length == 4) {
        //     setIsDeliveryPickup(false);
        //     brandStrg = uri.pathSegments.first;
        //     branchStrg = uri.pathSegments[1];
        //     tnStrg = uri.pathSegments[2];
        //     if (uri.pathSegments[3] == goBill) {
        //       toBill = goBill;
        //     } else if (uri.pathSegments[3].length == 32) {
        //       // its uuid or not

        //       tokenUser = uri.pathSegments[3];
        //       isExcelso = true;
        //     }
        //     return MaterialPageRoute(
        //       builder: (_) => Splash(
        //         branch: branchStrg,
        //         brand: brandStrg,
        //         tn: tnStrg,
        //         role: roleStrg,
        //         cashierName: cashierNameStrg,
        //         toBill: toBill,
        //         orderId: orderId,
        //         token: tokenUser,
        //       ),
        //     );
        //   } else if (uri.pathSegments.length == 5) {
        //     setIsDeliveryPickup(false);
        //     brandStrg = uri.pathSegments.first;
        //     branchStrg = uri.pathSegments[1];
        //     tnStrg = uri.pathSegments[2];
        //     if (uri.pathSegments[3] == 'cashier') {
        //       // roleStrg = 'cashier';
        //       roleStrg = 'customer';
        //       cashierNameStrg = uri.pathSegments[4];
        //     } else if (uri.pathSegments[3].length == 32 &&
        //         uri.pathSegments[4] == goBill) {
        //       tokenUser = uri.pathSegments[3];
        //       isExcelso = true;
        //       toBill = goBill;
        //     }
        //     return MaterialPageRoute(
        //       builder: (_) => Splash(
        //         branch: branchStrg,
        //         brand: brandStrg,
        //         tn: tnStrg,
        //         role: roleStrg,
        //         cashierName: cashierNameStrg,
        //         toBill: toBill,
        //         orderId: orderId,
        //         token: tokenUser,
        //       ),
        //     );
        //   }
        //   return null;
        // },
      ),
    );
  }
}
