import 'package:flutter/material.dart';
import 'package:pharmacy_mobile/auth/auth_service.dart';
import 'package:pharmacy_mobile/pages/customer_page.dart';
import 'package:pharmacy_mobile/pages/index_page.dart';
import 'package:pharmacy_mobile/pages/main_page.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

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

  @override
  Widget build(BuildContext context) {
    final authService = AuthService();

    return StreamBuilder(
        stream: Supabase.instance.client.auth.onAuthStateChange,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(
                  color: Colors.green,
                ),
              ),
            );
          }

          final session = snapshot.hasData ? snapshot.data!.session : null;

          if (session != null) {
            final user = authService.getCurrentUser();

            if (user != null && user.contains('admin')) {
              return const MainPage();
            } else {
              return const CustomerPage();
            }
          } else {
            return const IndexPage();
          }
        });
  }
}
