import 'package:firebase_core/firebase_core.dart';
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:go_router/go_router.dart';
import 'package:syncrow_web/firebase_options_prod.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/routines/bloc/create_routine_bloc/create_routine_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.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/navigation_service.dart';
import 'package:syncrow_web/utils/theme/theme.dart';

Future<void> main() async {
  try {
    const environment = String.fromEnvironment(
      'FLAVOR',
      defaultValue: 'production',
    );
    await dotenv.load(fileName: '.env.$environment');
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(
      options: DefaultFirebaseOptionsStaging.currentPlatform,
    );
    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 {
      final 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) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<CreateRoutineBloc>(
            create: (context) => CreateRoutineBloc(),
          ),
          BlocProvider(create: (context) => HomeBloc()..add(FetchUserInfo())),
          BlocProvider<VisitorPasswordBloc>(
            create: (context) => VisitorPasswordBloc(),
          ),
          BlocProvider<RoutineBloc>(
            create: (context) => RoutineBloc(),
          ),
          BlocProvider<SpaceTreeBloc>(
            create: (context) => SpaceTreeBloc(),
          ),
        ],
        child: MaterialApp.router(
          debugShowCheckedModeBanner: false,
          scrollBehavior: const MaterialScrollBehavior().copyWith(
            dragDevices: {
              PointerDeviceKind.mouse,
              PointerDeviceKind.touch,
              PointerDeviceKind.stylus,
              PointerDeviceKind.unknown,
            },
          ),
          key: NavigationService.navigatorKey,
          // scaffoldMessengerKey: NavigationService.snackbarKey,
          theme: myTheme,
          routerConfig: _router,
        ));
  }
}
