import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:phone_login/auth/auth_state.dart';
import 'package:phone_login/auth/phone_input_screen.dart';
import 'package:phone_login/auth/sms_verification_screen.dart';
import 'package:phone_login/home/home_screen.dart';
import 'package:phone_login/profile/profile_screen.dart';
import 'package:phone_login/services/auth_service.dart';
import 'package:phone_login/theme/app_theme.dart';
import 'package:provider/provider.dart';

final _router = GoRouter(
  routes: [
    GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
    GoRoute(
      path: '/login',
      builder: (context, state) => const PhoneInputScreen(),
    ),
    GoRoute(
      path: '/sms_verify',
      builder: (context, state) => const SmsVerificationScreen(),
    ),
    GoRoute(
      path: '/profile',
      builder: (context, state) => const ProfileScreen(),
    ),
  ],
  redirect: (BuildContext context, GoRouterState state) {
    final authState = Provider.of<AuthState>(context, listen: false);
    final bool loggedIn = authState.isLoggedIn;
    final bool loggingIn =
        state.matchedLocation == '/login' ||
        state.matchedLocation == '/sms_verify';

    if (!loggedIn && !loggingIn) {
      return '/login';
    }

    if (loggedIn && loggingIn) {
      return '/';
    }

    return null;
  },
);

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

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthState(FirebaseAuthService()),
      child: MaterialApp.router(
        routerConfig: _router,
        debugShowCheckedModeBanner: false,
        title: 'Phone Login App',
        theme: AppTheme.lightTheme,
        darkTheme: AppTheme.darkTheme,
        themeMode: ThemeMode.system,
      ),
    );
  }
}
