import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// ignore: depend_on_referenced_packages
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';

// 🚀 NEW: FIREBASE IMPORTS
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Import your core architecture
import 'core/constants/app_colors.dart';
import 'core/services/database_service.dart';
import 'features/auth/reconnection_screen.dart'; 
import 'features/admin/screens/admin_home_screen.dart'; // <-- ADDED ADMIN IMPORT
import 'features/map_search/models/post_model.dart'; 
import 'features/map_search/models/user_model.dart';
// ADDED IMPORTS FOR API CACHING
import 'core/models/api_cache.dart';
import 'core/networks/api_client.dart';

// Global Isar database instance for offline-first feed caching
late Isar isarDB;

void main() async {
  // 1. Ensure bindings are initialized for async code
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();

  // 2. Keep the native splash screen up while the app boots
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  // 3. Set device orientation and UI overlay styles
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    ),
  );

  // 4. Get directory first (needed for Isar)
  final dir = await getApplicationDocumentsDirectory();

  // 🚀 5. RUN HEAVY TASKS CONCURRENTLY (MASSIVE SPEED BOOST)
  // Instead of waiting for one to finish before starting the next, we launch them all at once.
  final initResults = await Future.wait([
    Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform),
    Isar.open(
      [PostModelSchema, ApiCacheSchema, UserModelSchema], 
      directory: dir.path, 
      name: 'skillConnectDB'
    ),
    DatabaseService.init(),
  ]);

  // Extract the initialized Isar instance from the parallel results (it is index 1 in the list above)
  isarDB = initResults[1] as Isar;
  ApiClient.isar = isarDB;

  // 6. Check if a user is already saved in the local database
  // This must run after DatabaseService.init() finishes.
  final currentUser = await DatabaseService.getLocalUser();
  
  Widget startingScreen = const ReconnectionScreen(); 

  if (currentUser != null && currentUser.email.isNotEmpty) {
    
    // --- FORCE LOAD THE TOKEN INTO API CLIENT IMMEDIATELY ---
    ApiClient.bearerToken = await DatabaseService.getToken();
    debugPrint("🔑 Loaded Token in main.dart: ${ApiClient.bearerToken}");

    final String role = currentUser.role.toLowerCase();
    
    if (role.contains('admin') || role.contains('super') || role.contains('staff')) {
      startingScreen = const AdminHomeScreen();
    } else {
      startingScreen = const ReconnectionScreen();
    }
  }

  // 7. Boot complete, remove the native splash screen
  FlutterNativeSplash.remove();

  // 8. Run the app and pass the calculated starting screen
  runApp(SkillConnectApp(initialScreen: startingScreen));
}

class SkillConnectApp extends StatelessWidget {
  final Widget initialScreen;

  const SkillConnectApp({super.key, required this.initialScreen});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SkillConnect ZM Admin',
      debugShowCheckedModeBanner: false, 
      
      theme: ThemeData(
        useMaterial3: true,
        scaffoldBackgroundColor: AppColors.background,
        colorScheme: ColorScheme.fromSeed(
          seedColor: AppColors.primaryGreen,
          primary: AppColors.primaryGreen,
          secondary: AppColors.accentYellow,
          surface: AppColors.surface,
          error: AppColors.error,
        ),
        
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.transparent,
          elevation: 0,
          centerTitle: true,
          iconTheme: IconThemeData(color: AppColors.textPrimary),
          titleTextStyle: TextStyle(
            color: AppColors.textPrimary,
            fontSize: 18,
            fontWeight: FontWeight.w700,
          ),
        ),

        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: Colors.white,
          contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: BorderSide(color: Colors.grey.shade200),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: BorderSide(color: Colors.grey.shade200),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: const BorderSide(color: AppColors.primaryGreen, width: 2),
          ),
          errorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: const BorderSide(color: AppColors.error, width: 1.5),
          ),
        ),
      ),
      
      // Routes perfectly based on the offline credentials checked during boot
      home: initialScreen,
    );
  }
}


school file