import 'package:em2rp/providers/users_provider.dart';
import 'package:em2rp/providers/event_provider.dart';
import 'package:em2rp/providers/equipment_provider.dart';
import 'package:em2rp/providers/container_provider.dart';
import 'package:em2rp/providers/maintenance_provider.dart';
import 'package:em2rp/providers/alert_provider.dart';
import 'package:em2rp/utils/auth_guard_widget.dart';
import 'package:em2rp/utils/performance_monitor.dart';
import 'package:em2rp/views/alerts_page.dart';
import 'package:em2rp/views/calendar_page.dart';
import 'package:em2rp/views/login_page.dart';
import 'package:em2rp/views/equipment_management_page.dart';
import 'package:em2rp/views/container_management_page.dart';
import 'package:em2rp/views/maintenance_management_page.dart';
import 'package:em2rp/views/container_form_page.dart';
import 'package:em2rp/views/container_detail_page.dart';
import 'package:em2rp/views/event_preparation_page.dart';
import 'package:em2rp/views/event_statistics_page.dart';
import 'package:em2rp/models/container_model.dart';
import 'package:em2rp/models/event_model.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'utils/colors.dart';
import 'views/my_account_page.dart';
import 'views/user_management_page.dart';
import 'package:provider/provider.dart';
import 'providers/local_user_provider.dart';
import 'views/reset_password_page.dart';
import 'config/env.dart';
import 'services/update_service.dart';
import 'views/widgets/common/update_dialog.dart';
import 'config/api_config.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // Configuration des émulateurs en mode développement
  if (ApiConfig.isDevelopment) {
    print('🔧 Mode développement activé - Utilisation des émulateurs');

    // Configurer l'émulateur Auth
    await FirebaseAuth.instance.useAuthEmulator('localhost', 9199);
    print('✓ Auth émulateur configuré: localhost:9199');

    // Configurer l'émulateur Firestore
    FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8088);
    print('✓ Firestore émulateur configuré: localhost:8088');
  }

  await FirebaseAuth.instance.setPersistence(Persistence.LOCAL);

  runApp(
    MultiProvider(
      providers: [
        // LocalUserProvider pour la gestion de l'authentification
        ChangeNotifierProvider<LocalUserProvider>(
            create: (context) => LocalUserProvider()),

        // UsersProvider migré vers l'API
        ChangeNotifierProvider<UsersProvider>(
          create: (context) => UsersProvider(),
        ),

        // EventProvider migré vers l'API
        ChangeNotifierProvider<EventProvider>(
          create: (context) => EventProvider(),
        ),

        // EquipmentProvider migré vers l'API
        ChangeNotifierProvider<EquipmentProvider>(
          create: (context) => EquipmentProvider(),
        ),

        // ContainerProvider migré vers l'API
        ChangeNotifierProvider<ContainerProvider>(
          create: (context) => ContainerProvider(),
        ),

        // MaintenanceProvider migré vers l'API
        ChangeNotifierProvider<MaintenanceProvider>(
          create: (context) => MaintenanceProvider(),
        ),
        ChangeNotifierProvider<AlertProvider>(
          create: (context) => AlertProvider(),
        ),
      ],
      child: const MyApp(),
    ),
  );
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'EM2 Hub',
      theme: ThemeData(
      primarySwatch: Colors.red,
      primaryColor: AppColors.noir,
      colorScheme:
          ColorScheme.fromSwatch().copyWith(secondary: AppColors.rouge),
      textTheme: const TextTheme(
        bodyMedium: TextStyle(color: AppColors.noir),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: AppColors.noir),
        ),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: AppColors.gris),
        ),
        labelStyle: TextStyle(color: AppColors.noir),
        hintStyle: TextStyle(color: AppColors.gris),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            foregroundColor: AppColors.blanc,
            backgroundColor: AppColors.noir,
          ),
        ),
      ),
      locale: const Locale('fr', 'FR'),
      supportedLocales: const [
        Locale('fr', 'FR'),
      ],
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      initialRoute: '/',
      routes: {
        '/': (context) => const AutoLoginWrapper(),
        '/login': (context) => const LoginPage(),
        '/alerts': (context) => const AuthGuard(child: AlertsPage()),
        '/calendar': (context) => const AuthGuard(child: CalendarPage()),
        '/my_account': (context) => const AuthGuard(child: MyAccountPage()),
        '/user_management': (context) => const AuthGuard(
            requiredPermission: "view_all_users", child: UserManagementPage()),
        '/reset_password': (context) {
          final args = ModalRoute.of(context)!.settings.arguments
              as Map<String, dynamic>;
          return ResetPasswordPage(
            email: args['email'] as String,
            actionCode: args['actionCode'] as String,
          );
        },
        '/equipment_management': (context) => const AuthGuard(
            requiredPermission: "view_equipment",
            child: EquipmentManagementPage()),
        '/container_management': (context) => const AuthGuard(
            requiredPermission: "view_equipment",
            child: ContainerManagementPage()),
        '/maintenance_management': (context) => const AuthGuard(
            requiredPermission: "manage_maintenances",
            child: MaintenanceManagementPage()),
        '/container_form': (context) {
          final args = ModalRoute.of(context)?.settings.arguments;
          return AuthGuard(
            requiredPermission: "manage_equipment",
            child: ContainerFormPage(
              container: args as ContainerModel?,
            ),
          );
        },
        '/container_detail': (context) {
          final container = ModalRoute.of(context)!.settings.arguments as ContainerModel;
          return AuthGuard(
            requiredPermission: "view_equipment",
            child: ContainerDetailPage(container: container),
          );
        },
        '/event_preparation': (context) {
          final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
          final event = args['event'] as EventModel;
          return AuthGuard(
            child: EventPreparationPage(
              initialEvent: event,
            ),
          );
        },
        '/event_statistics': (context) => const AuthGuard(
            requiredPermission: 'generate_reports', child: EventStatisticsPage()),
      },
    );
  }
}

class AutoLoginWrapper extends StatefulWidget {
  const AutoLoginWrapper({super.key});

  @override
  State<AutoLoginWrapper> createState() => _AutoLoginWrapperState();
}

class _AutoLoginWrapperState extends State<AutoLoginWrapper> {
  @override
  void initState() {
    super.initState();
    // Attendre la fin du premier build avant de naviguer
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _autoLogin();
      // Vérifier les mises à jour après un délai pour ne pas interférer avec l'autologin
      _checkForUpdateDelayed();
    });
  }

  /// Vérifie les mises à jour après un délai
  Future<void> _checkForUpdateDelayed() async {
    try {
      // Attendre que l'app soit complètement chargée (navigation effectuée, etc.)
      await Future.delayed(const Duration(seconds: 3));

      if (!mounted) return;

      final updateInfo = await UpdateService.checkForUpdate();

      if (updateInfo != null && mounted) {
        // Attendre encore un peu pour être sûr que le bon contexte est disponible
        await Future.delayed(const Duration(milliseconds: 500));

        if (mounted) {
          showDialog(
            context: context,
            barrierDismissible: !updateInfo.forceUpdate,
            builder: (context) => UpdateDialog(updateInfo: updateInfo),
          );
        }
      }
    } catch (e) {
      print('[AutoLoginWrapper] Error checking for update: $e');
    }
  }

  Future<void> _autoLogin() async {
    PerformanceMonitor.start('App.autoLogin');
    try {
      final localAuthProvider =
          Provider.of<LocalUserProvider>(context, listen: false);

      // Vérifier si l'utilisateur est déjà connecté
      if (FirebaseAuth.instance.currentUser == null && Env.isDevelopment) {
        PerformanceMonitor.start('App.signIn');
        // Connexion automatique en mode développement
        await localAuthProvider.signInWithEmailAndPassword(
          Env.devAdminEmail,
          Env.devAdminPassword,
        );
        PerformanceMonitor.end('App.signIn');
      }

      if (mounted) {
        // MODIFIÉ : Vérifier si une route spécifique est demandée dans l'URL
        // En Flutter Web, on peut vérifier window.location.hash
        final currentUri = Uri.base;
        final fragment = currentUri.fragment; // Ex: "/alerts" si URL est /#/alerts

        print('[AutoLoginWrapper] Fragment URL: $fragment');

        // Navigation immédiate sans attendre le chargement des données
        if (fragment.isNotEmpty && fragment != '/' && fragment != '/calendar') {
          print('[AutoLoginWrapper] Redirection vers: $fragment');
          Navigator.of(context).pushReplacementNamed(fragment);
        } else {
          // Route par défaut : calendrier
          print('[AutoLoginWrapper] Redirection vers: /calendar (défaut)');
          Navigator.of(context).pushReplacementNamed('/calendar');
        }

        PerformanceMonitor.end('App.autoLogin');
        PerformanceMonitor.printSummary();

        // Charger les données utilisateur en arrière-plan
        localAuthProvider.loadUserData().catchError((e) {
          print('Error loading user data: $e');
        });
      }
    } catch (e) {
      print('Auto login failed: $e');
      PerformanceMonitor.end('App.autoLogin');
      if (mounted) {
        Navigator.of(context).pushReplacementNamed('/login');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo de l'application
            Image.asset(
              'assets/logos/RectangleLogoBlack.png',
              width: 200,
              height: 200,
              fit: BoxFit.contain,
              errorBuilder: (context, error, stackTrace) {
                return const Icon(
                  Icons.event_available,
                  size: 80,
                  color: AppColors.rouge,
                );
              },
            ),
            const SizedBox(height: 40),
            const CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(AppColors.rouge),
            ),
            const SizedBox(height: 20),
            const Text(
              'Chargement...',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
