import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_event.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/theme/theme.dart';

Future<void> main() async {
  try {
    const environment =
        String.fromEnvironment('FLAVOR', defaultValue: 'development');
    await dotenv.load(fileName: '.env.$environment');
    WidgetsFlutterBinding.ensureInitialized();
    initialSetup();
  } catch (_) {}
  runApp(MyApp());
}

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

  final GoRouter _router = GoRouter(
    initialLocation: RoutesConst.auth,
    routes: AppRoutes.getRoutes(),
    redirect: (context, state) async {
      String checkToken = await AuthBloc.getTokenAndValidate();
      final loggedIn = checkToken == 'Success';
      final goingToLogin = state.uri.toString() == RoutesConst.auth;

      if (!loggedIn && !goingToLogin) return RoutesConst.auth;
      if (loggedIn && goingToLogin) return RoutesConst.home;

      return null;
    },
  );

  @override
  Widget build(BuildContext context) {
    //HomeBloc.fetchUserInfo();
    return MultiBlocProvider(
        providers: [
          BlocProvider(
              create: (context) => HomeBloc()..add(const FetchUserInfo())),
          BlocProvider<VisitorPasswordBloc>(
            create: (context) => VisitorPasswordBloc(),
          )
        ],
        child: MaterialApp.router(
          debugShowCheckedModeBanner: false,
          scrollBehavior: const MaterialScrollBehavior().copyWith(
            dragDevices: {
              PointerDeviceKind.mouse,
              PointerDeviceKind.touch,
              PointerDeviceKind.stylus,
              PointerDeviceKind.unknown,
            },
          ),
          theme: myTheme,
          routerConfig: _router,
        ));
  }
}
