import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'auth_provider.dart' as MyAppAuthProvider;
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'login_screen.dart';
import 'register_screen.dart';
import 'home_screen.dart';
import 'monitoring_sensor_page.dart';
import 'histori_data_page.dart';
import 'mode_kontrol_page.dart';
import 'artikel_page.dart';

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

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

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

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => MyAppAuthProvider.AuthProvider(FirebaseAuth.instance),
        ),
        StreamProvider<User?>(
          create: (context) =>
              context.read<MyAppAuthProvider.AuthProvider>().authStateChanges,
          initialData: null,
        ),
      ],
      child: MaterialApp(
        navigatorObservers: [routeObserver],
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        theme: ThemeData(
          colorScheme:
              ColorScheme.fromSeed(seedColor: Color.fromARGB(255, 109, 66, 5)),
          useMaterial3: true,
        ),
        initialRoute: '/login',
        routes: {
          '/login': (context) => const LoginScreen(),
          '/register': (context) => const RegisterScreen(),
          '/home': (context) => HomeWrapper(),
          '/monitoringSensor': (context) =>
              const MonitoringSensorPage(title: 'Monitor Sensor'),
          '/historiData': (context) =>
              const HistoriDataPage(title: 'Histori Data'),
          '/modeKontrol': (context) =>
              const ModeKontrolPage(title: 'Mode Kontrol'),
          '/artikel': (context) => const ArtikelPage(title: 'Artikel'),
        },
      ),
    );
  }
}

class HomeWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User?>(context);
    if (user != null) {
      final userName = user.displayName ?? 'CropLink IoT';
      return MyHomePage(userName: userName);
    } else {
      return const LoginScreen();
    }
  }
}
