import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

import 'package:permission_handler/permission_handler.dart';

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

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import 'firebase_options.dart';

import 'login_page.dart';
import 'dashboard_admin.dart';
import 'dashboard_guru.dart';
import 'dashboard_ortu.dart';

// ================= NOTIF =================
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

// ================= MAIN =================
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

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

  // ================= ANDROID ONLY =================
  if (!kIsWeb) {
    if (defaultTargetPlatform == TargetPlatform.android) {
      await Permission.notification.request();
      await Permission.scheduleExactAlarm.request();
    }

    const AndroidInitializationSettings androidSettings =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    const InitializationSettings settings = InitializationSettings(
      android: androidSettings,
    );

    await flutterLocalNotificationsPlugin.initialize(settings: settings);
  }

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,

      home: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),

        builder: (context, snapshot) {
          // ================= LOADING =================
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }

          // ================= BELUM LOGIN =================
          if (!snapshot.hasData) {
            return const LoginPage();
          }

          final user = snapshot.data!;

          // ================= CEK ROLE =================
          return FutureBuilder<DocumentSnapshot>(
            future: FirebaseFirestore.instance
                .collection('users')
                .doc(user.uid)
                .get(),

            builder: (context, userSnap) {
              // Loading data user
              if (userSnap.connectionState == ConnectionState.waiting) {
                return const Scaffold(
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }

              // Jika dokumen user tidak ada
              if (!userSnap.hasData || !userSnap.data!.exists) {
                return const Scaffold(
                  body: Center(
                    child: Text('Data pengguna tidak ditemukan'),
                  ),
                );
              }

              final data =
                  userSnap.data!.data() as Map<String, dynamic>? ?? {};

              final role = data['role'] ?? 'ortu';

              // ================= ADMIN =================
              if (role == 'admin') {
                return const DashboardAdmin();
              }

              // ================= GURU =================
              if (role == 'guru') {
                return const DashboardGuru();
              }

              // ================= ORTU =================
              return const DashboardOrtu();
            },
          );
        },
      ),
    );
  }
}