import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../features/auth/auth_provider.dart';
import '../features/auth/login_screen.dart'; // To be created
import '../features/customer/home_screen.dart'; // To be created
import '../features/worker/worker_home_screen.dart'; // To be created
import '../features/customer/post_job_screen.dart';

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

  return GoRouter(
    initialLocation: '/login',
    redirect: (context, state) {
      final isLoggedIn = authState.value != null;
      final isLoggingIn = state.uri.toString() == '/login';

      if (!isLoggedIn && !isLoggingIn) return '/login';
      
      if (isLoggedIn && isLoggingIn) {
        final role = authState.value!['role'];
        if (role == 'worker') return '/worker-home';
        return '/customer-home';
      }

      return null;
    },
    routes: [
      GoRoute(
        path: '/login',
        builder: (context, state) => const LoginScreen(),
      ),
      GoRoute(
        path: '/customer-home',
        builder: (context, state) => const CustomerHomeScreen(),
      ),
      GoRoute(
        path: '/worker-home',
        builder: (context, state) => const WorkerHomeScreen(),
      ),
      GoRoute(
        path: '/post-job',
        builder: (context, state) {
          final service = state.extra as Map<String, dynamic>;
          return PostJobScreen(service: service);
        },
      ),
    ],
  );
});
