import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../providers/auth_provider.dart';
import 'app_router.dart';

// Bridges Riverpod auth state changes to GoRouter's Listenable interface
class _AuthRouterNotifier extends ChangeNotifier {
  _AuthRouterNotifier(this._ref) {
    _ref.listen<AuthState>(authProvider, (_, __) => notifyListeners());
  }
  final Ref _ref;
}

final routerProvider = Provider<GoRouter>((ref) {
  final notifier = _AuthRouterNotifier(ref);

  return GoRouter(
    refreshListenable: notifier,
    initialLocation: routeWelcome,
    redirect: (context, state) {
      final auth = ref.read(authProvider);

      if (auth.isLoading) return null;

      final loc = state.matchedLocation;
      final onLoginOrRegister =
          loc == routeSignIn || loc == routeSignUp || loc == routeWelcome;
      final onAuthPage = onLoginOrRegister || loc == routeOnboarding;

      if (!auth.isAuthenticated) {
        return onAuthPage ? null : routeWelcome;
      }

      // Authenticated but no tenant → onboarding
      if (auth.activeTenant == null) {
        return loc == routeOnboarding ? null : routeOnboarding;
      }

      final isLab = auth.activeTenant!.tenant.isLab;

      if (onAuthPage) {
        return isLab ? routeLabDashboard : routeClinicDashboard;
      }

      if (isLab && loc.startsWith('/clinic')) return routeLabDashboard;
      if (!isLab && loc.startsWith('/lab')) return routeClinicDashboard;

      return null;
    },
    routes: buildRoutes(),
  );
});
