import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:recolecta_app/features/admin/admin_screen.dart';
import 'package:recolecta_app/features/auth/login_page.dart';
import 'package:recolecta_app/features/splash/splash_screen.dart';
import 'package:recolecta_app/features/auth/register_page.dart';
import 'package:recolecta_app/features/driver/driver_shell.dart';
import 'package:recolecta_app/features/driver/screens/driver_collections_screen.dart';
import 'package:recolecta_app/features/driver/screens/driver_home_screen.dart';
import 'package:recolecta_app/features/driver/screens/driver_incident_screen.dart';
import 'package:recolecta_app/features/home/citizen_home_screen.dart';
import 'package:recolecta_app/features/home/citizen_shell.dart';
import 'package:recolecta_app/features/home/house_screen.dart';
import 'package:recolecta_app/features/alerts/alerts_screen.dart';
import 'package:recolecta_app/features/profile/profile_screen.dart';
import 'package:recolecta_app/features/feedback/feedback_screen.dart';
import 'package:recolecta_app/features/profile/edit_profile_screen.dart';
import 'package:recolecta_app/features/separation_guide/screens/category_detail_screen.dart';
import 'package:recolecta_app/features/separation_guide/screens/separation_guide_screen.dart';
import 'package:recolecta_app/core/services/auth_controller.dart';
import '../../features/addresses/add_address_page.dart';
import '../../features/notifications/notifications_screen.dart';
import '../../features/quiz/quiz_screen.dart';
import '../../features/help/screens/help_faq_screen.dart';
import '../../features/incidents/screens/report_issue_screen.dart';
import '../../features/about/screens/about_screen.dart';

/// Clave global del Navigator raíz. La expone GoRouter y la usa
/// `NotificationService` para navegar a `/notifications` cuando el usuario
/// toca un push (foreground, background o terminated).
final rootNavigatorKey = GlobalKey<NavigatorState>();

final routerProvider = Provider<GoRouter>((ref) {
  final authState = ref.watch(authControllerProvider);

  return GoRouter(
    navigatorKey: rootNavigatorKey,
    initialLocation: '/splash',
    redirect: (BuildContext context, GoRouterState state) {
      final isAuthenticated = authState.value?.isAuthenticated ?? false;
      final role = authState.value?.userRole;

      final isPublicRoute =
          state.matchedLocation == '/splash' ||
          state.matchedLocation == '/login' ||
          state.matchedLocation == '/register';

      if (!isAuthenticated) {
        return isPublicRoute ? null : '/login';
      }

      if (isPublicRoute) {
        switch (role) {
          case 'admin':
            return '/admin';
          case 'driver':
            return '/driver';
          case 'citizen':
            return '/home';
          default:
            return '/login';
        }
      }

      return null;
    },
    routes: [
      GoRoute(
        path: '/splash',
        builder: (context, state) => const SplashScreen(),
      ),
      GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
      GoRoute(
        path: '/register',
        builder: (context, state) => const RegisterPage(),
      ),
      GoRoute(
        path: '/edit-profile',
        builder: (context, state) => const EditProfileScreen(),
      ),

      // ── Admin ─────────────────────────────────────────────────────────────
      GoRoute(path: '/admin', builder: (context, state) => const AdminScreen()),

      // ── Chofer ────────────────────────────────────────────────────────────
      ShellRoute(
        builder: (context, state, child) => DriverShell(child: child),
        routes: [
          GoRoute(
            path: '/driver',
            builder: (context, state) => const DriverHomeScreen(),
          ),
          GoRoute(
            path: '/driver/collections',
            builder: (context, state) => const DriverCollectionsScreen(),
          ),
          GoRoute(
            path: '/driver/incident',
            builder: (context, state) => const DriverIncidentScreen(),
          ),
        ],
      ),

      // ── Ciudadano — 4 tabs ────────────────────────────────────────────────
      ShellRoute(
        builder: (context, state, child) => CitizenShell(child: child),
        routes: [
          GoRoute(
            path: '/home',
            builder: (context, state) => const CitizenHomeScreen(),
          ),
          GoRoute(
            path: '/alerts',
            builder: (context, state) => const AlertsScreen(),
          ),
          GoRoute(
            path: '/house',
            builder: (context, state) => const MyHouseScreen(),
          ),
          GoRoute(
            path: '/profile',
            builder: (context, state) => const ProfileScreen(),
          ),
          // Rutas secundarias accesibles con el nav bar visible
          GoRoute(
            path: '/feedback',
            builder: (context, state) => const FeedbackScreen(),
          ),
          GoRoute(
            path: '/add-address',
            builder: (context, state) => const AddAddressPage(),
          ),
          GoRoute(
            path: '/guide',
            builder: (context, state) => const SeparationGuideScreen(),
            routes: [
              GoRoute(
                path: ':categoryId',
                builder: (context, state) => CategoryDetailScreen(
                  categoryId: state.pathParameters['categoryId']!,
                ),
              ),
            ],
          ),
        ],
      ),

      // ── Pantallas sueltas (sin shell) ─────────────────────────────────────
      GoRoute(
        path: '/notifications',
        builder: (context, state) => const NotificationsScreen(),
      ),
      GoRoute(path: '/quiz', builder: (context, state) => const QuizScreen()),
      GoRoute(
        path: '/help',
        builder: (context, state) => const HelpFaqScreen(),
      ),
      GoRoute(
        path: '/report-issue',
        builder: (context, state) => const ReportIssueScreen(),
      ),
      GoRoute(path: '/about', builder: (context, state) => const AboutScreen()),
    ],
  );
});
