import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../constants/app_constants.dart';
import '../models/marketplace.dart';
import '../providers/auth_provider.dart';
import '../../features/auth/screens/splash_screen.dart';
import '../../features/auth/screens/landing_screen.dart';
import '../../features/auth/screens/role_screen.dart';
import '../../features/auth/screens/employee_login_screen.dart';
import '../../features/dashboard/screens/home_screen.dart';
import '../../features/dashboard/screens/vehicles_screen.dart';
import '../../features/dashboard/screens/vehicle_detail_screen.dart';
import '../../features/dashboard/screens/vehicle_form_screen.dart';
import '../../features/dashboard/screens/reservations_screen.dart';
import '../../features/dashboard/screens/reservation_detail_screen.dart';
import '../../features/dashboard/screens/new_reservation_screen.dart';
import '../../features/dashboard/screens/customers_screen.dart';
import '../../features/dashboard/screens/customer_detail_screen.dart';
import '../../features/dashboard/screens/customer_form_screen.dart';
import '../../features/dashboard/screens/notifications_screen.dart';
import '../../features/dashboard/screens/online_reservations_screen.dart';
import '../../features/dashboard/screens/contract_screen.dart';
import '../../features/dashboard/screens/contracts_screen.dart';
import '../../features/dashboard/screens/offers_screen.dart';
import '../../features/dashboard/screens/reports_screen.dart';
import '../../features/dashboard/screens/settings_screen.dart';
import '../../features/dashboard/screens/team_screen.dart';
import '../../features/client/screens/client_home_screen.dart';
import '../../features/client/screens/client_vehicle_detail_screen.dart';
import '../../features/client/screens/booking_screen.dart';
import '../../features/client/screens/booking_confirmation_screen.dart';
import '../../features/client/screens/my_bookings_screen.dart';
import '../../features/client/models/booking_result.dart';
import '../../features/agency_webview/screens/agency_dashboard_webview_screen.dart';

final routerProvider = Provider<GoRouter>((ref) {
  final router = GoRouter(
    initialLocation: '/splash',
    redirect: (context, state) {
      final auth = ref.read(authProvider);
      final status = auth.status;
      final loc = state.matchedLocation;
      final isSplash = loc == '/splash';
      final isLanding = loc == '/landing';
      final isLogin = loc.startsWith('/login');

      if (status == AuthStatus.unknown) {
        return isSplash ? null : '/splash';
      }

      if (isSplash) {
        if (status == AuthStatus.authenticated) {
          return auth.userType == AppConstants.userTypeEmployee
              ? '/dashboard'
              : '/client';
        }
        return '/landing';
      }

      if (status == AuthStatus.unauthenticated) {
        if (isLanding ||
            isLogin ||
            loc.startsWith('/client') ||
            loc == '/role' ||
            loc == '/agency') {
          return null;
        }
        return '/landing';
      }

      if (status == AuthStatus.authenticated) {
        if (isLogin) {
          return auth.userType == AppConstants.userTypeEmployee
              ? '/dashboard'
              : '/client';
        }
      }
      return null;
    },
    routes: [
      GoRoute(path: '/splash', builder: (context, _) => const SplashScreen()),
      GoRoute(path: '/landing', builder: (context, _) => const LandingScreen()),
      GoRoute(path: '/role', builder: (context, _) => const RoleScreen()),
      GoRoute(
        path: '/login/employee',
        builder: (context, _) => const EmployeeLoginScreen(),
      ),
      GoRoute(path: '/dashboard', builder: (context, _) => const HomeScreen()),
      GoRoute(
        path: '/dashboard/vehicles',
        builder: (context, _) => const VehiclesScreen(),
      ),
      GoRoute(
        path: '/dashboard/reservations',
        builder: (context, _) => const ReservationsScreen(),
      ),
      GoRoute(
        path: '/dashboard/customers',
        builder: (context, _) => const CustomersScreen(),
      ),
      GoRoute(
        path: '/dashboard/vehicles/:id',
        builder: (_, state) =>
            VehicleDetailScreen(id: state.pathParameters['id']!),
      ),
      GoRoute(
        path: '/dashboard/reservations/:id',
        builder: (_, state) =>
            ReservationDetailScreen(id: state.pathParameters['id']!),
      ),
      GoRoute(
        path: '/dashboard/reservations/:id/contract',
        builder: (_, state) =>
            ContractScreen(reservationId: state.pathParameters['id']!),
      ),
      GoRoute(
        path: '/dashboard/customers/:id',
        builder: (_, state) =>
            CustomerDetailScreen(id: state.pathParameters['id']!),
      ),
      GoRoute(
        path: '/dashboard/notifications',
        builder: (context, _) => const NotificationsScreen(),
      ),
      GoRoute(
        path: '/dashboard/online-reservations',
        builder: (context, _) => const OnlineReservationsScreen(),
      ),
      GoRoute(
        path: '/dashboard/contracts',
        builder: (context, _) => const ContractsScreen(),
      ),
      GoRoute(
        path: '/dashboard/offers',
        builder: (context, _) => const OffersScreen(),
      ),
      GoRoute(
        path: '/dashboard/reports',
        builder: (context, _) => const ReportsScreen(),
      ),
      GoRoute(
        path: '/dashboard/settings',
        builder: (context, _) => const SettingsScreen(),
      ),
      GoRoute(
        path: '/dashboard/team',
        builder: (context, _) => const TeamScreen(),
      ),
      GoRoute(
        path: '/client',
        builder: (context, _) => const ClientHomeScreen(),
      ),
      GoRoute(
        path: '/client/bookings',
        builder: (context, _) => const MyBookingsScreen(),
      ),
      GoRoute(
        path: '/client/vehicles/:id',
        builder: (_, state) => ClientVehicleDetailScreen(
          id: state.pathParameters['id']!,
          vehicle: state.extra as MarketplaceVehicle?,
        ),
      ),
      GoRoute(
        path: '/client/book/:vehicleId',
        builder: (_, state) => BookingScreen(
          vehicleId: state.pathParameters['vehicleId']!,
          vehicle: state.extra as MarketplaceVehicle?,
        ),
      ),
      GoRoute(
        path: '/booking-confirmation',
        builder: (_, state) {
          final result = state.extra as BookingResult?;
          if (result == null) return const ClientHomeScreen();
          return BookingConfirmationScreen(result: result);
        },
      ),
      GoRoute(
        path: '/agency',
        builder: (context, _) => const AgencyDashboardWebViewScreen(),
      ),
      GoRoute(
        path: '/dashboard/reservations/new',
        builder: (context, _) => const NewReservationScreen(),
      ),
      GoRoute(
        path: '/dashboard/vehicles/new',
        builder: (context, _) => const VehicleFormScreen(),
      ),
      GoRoute(
        path: '/dashboard/vehicles/:id/edit',
        builder: (_, state) => VehicleFormScreen(
          vehicle: state.extra as dynamic,
        ),
      ),
      GoRoute(
        path: '/dashboard/customers/new',
        builder: (context, _) => const CustomerFormScreen(),
      ),
      GoRoute(
        path: '/dashboard/customers/:id/edit',
        builder: (_, state) => CustomerFormScreen(
          customer: state.extra as dynamic,
        ),
      ),
    ],
  );

  ref.listen<AuthState>(authProvider, (_, _) => router.refresh());

  return router;
});
