import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';

import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/helpers/extensions/app_localization_delegate.dart';
import 'package:marco/helpers/services/auth_service.dart';
import 'package:marco/helpers/services/localizations/language.dart';
import 'package:marco/helpers/services/navigation_services.dart';
import 'package:marco/helpers/services/storage/local_storage.dart';
import 'package:marco/helpers/theme/app_theme.dart';
import 'package:marco/helpers/theme/theme_customizer.dart';
import 'package:marco/helpers/theme/app_notifier.dart';
import 'package:marco/routes.dart';

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

  Future<String> _getInitialRoute() async {
    try {
      if (!AuthService.isLoggedIn) {
        logSafe("User not logged in. Routing to /auth/login-option");
        return "/auth/login-option";
      }

      final bool hasMpin = LocalStorage.getIsMpin();
      logSafe("MPIN enabled: $hasMpin",  );

      if (hasMpin) {
        await LocalStorage.setBool("mpin_verified", false);
        logSafe("Routing to /auth/mpin-auth and setting mpin_verified to false");
        return "/auth/mpin-auth";
      } else {
        logSafe("MPIN not enabled. Routing to /dashboard");
        return "/dashboard";
      }
    } catch (e, stacktrace) {
      logSafe("Error determining initial route",
          level: LogLevel.error, error: e, stackTrace: stacktrace);
      return "/auth/login-option";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AppNotifier>(
      builder: (_, notifier, __) {
        return FutureBuilder<String>(
          future: _getInitialRoute(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              logSafe("FutureBuilder snapshot error",
                  level: LogLevel.error, error: snapshot.error);
              return const MaterialApp(
                home: Center(child: Text("Error determining route")),
              );
            }

            if (!snapshot.hasData) {
              return const MaterialApp(
                home: Center(child: CircularProgressIndicator()),
              );
            }

            return GetMaterialApp(
              debugShowCheckedModeBanner: false,
              theme: AppTheme.lightTheme,
              darkTheme: AppTheme.darkTheme,
              themeMode: ThemeCustomizer.instance.theme,
              navigatorKey: NavigationService.navigatorKey,
              initialRoute: snapshot.data!,
              getPages: getPageRoute(),
              builder: (context, child) {
                NavigationService.registerContext(context);
                return Directionality(
                  textDirection: AppTheme.textDirection,
                  child: child ?? const SizedBox(),
                );
              },
              localizationsDelegates: [
                AppLocalizationsDelegate(context),
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              supportedLocales: Language.getLocales(),
            );
          },
        );
      },
    );
  }
}
