import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'firebase_options.dart';
import 'screens/login_screen.dart';
import 'screens/dashboard_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MainApp());
}

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

  Future<Widget> _getStartPage() async {
    final user = FirebaseAuth.instance.currentUser;

    // Belum login
    if (user == null) {
      return const LoginScreen();
    }

    try {
      final doc = await FirebaseFirestore.instance
          .collection('users')
          .doc(user.uid)
          .get();

      // Data user tidak ditemukan
      if (!doc.exists) {
        await FirebaseAuth.instance.signOut();
        return const LoginScreen();
      }

      final role =
          (doc.data()?['role'] ?? 'user')
              .toString()
              .toLowerCase();

      // Admin harus login ulang setiap buka aplikasi
      if (role == 'admin') {
        await FirebaseAuth.instance.signOut();
        return const LoginScreen();
      }

      // User biasa langsung masuk dashboard
      return const DashboardScreen();
    } catch (e) {
      await FirebaseAuth.instance.signOut();
      return const LoginScreen();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FutureBuilder<Widget>(
        future: _getStartPage(),
        builder: (context, snapshot) {
          if (snapshot.connectionState ==
              ConnectionState.waiting) {
            return const Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }

          return snapshot.data ??
              const LoginScreen();
        },
      ),
    );
  }
}