import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../screens/login_screen.dart';
import '../screens/dashboard_screen.dart';
import '../screens/users_screen.dart';
import '../screens/groups_screen.dart';
import '../screens/group_detail_screen.dart';
import '../screens/notifications_screen.dart';

final appRouter = GoRouter(
  initialLocation: '/login',
  redirect: _guardRedirect,
  routes: [
    GoRoute(
      path: '/login',
      builder: (_, __) => const LoginScreen(),
    ),
    GoRoute(
      path: '/dashboard',
      builder: (_, __) => const DashboardScreen(),
    ),
    GoRoute(
      path: '/users',
      builder: (_, __) => const UsersScreen(),
    ),
    GoRoute(
      path: '/groups',
      builder: (_, __) => const GroupsScreen(),
    ),
    GoRoute(
      path: '/groups/:id',
      builder: (_, state) => GroupDetailScreen(
        groupId: state.pathParameters['id']!,
      ),
    ),
    GoRoute(
      path: '/notifications',
      builder: (_, __) => const NotificationsScreen(),
    ),
  ],
);

String? _guardRedirect(BuildContext context, GoRouterState state) {
  final auth = context.read<AuthProvider>();
  final isLoginPage = state.matchedLocation == '/login';

  if (!auth.isAuthenticated && !isLoginPage) {
    return '/login';
  }
  if (auth.isAuthenticated && isLoginPage) {
    return '/dashboard';
  }
  return null;
}
