import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';

import '../core/di/injection_container.dart';
import '../features/auth/presentation/pages/login_page.dart';
import '../features/auth/presentation/pages/register_page.dart';
import '../features/auth/presentation/viewmodels/auth_viewmodel.dart';
import '../features/onboarding/presentation/pages/onboarding_page.dart';
import '../features/onboarding/presentation/pages/setup_page.dart';
import '../features/settings/presentation/pages/settings_page.dart';
import '../features/settings/presentation/viewmodels/settings_viewmodel.dart';
import '../features/tasks/presentation/pages/calendar_page.dart';
import '../features/tasks/presentation/pages/daily_agenda_page.dart';
import '../features/tasks/presentation/pages/task_form_page.dart';

class AppRouter {
  static GoRouter? _router;

  static GoRouter get router {
    _router ??= _createRouter();
    return _router!;
  }

  static GoRouter _createRouter() {
    final authViewModel = getIt<AuthViewModel>();
    final settingsViewModel = getIt<SettingsViewModel>();

    return GoRouter(
      initialLocation: '/',
      redirect: (context, state) {
        final location = state.matchedLocation;

        // 1. Check if setup is completed
        if (!settingsViewModel.setupCompleted) {
          if (location != '/setup') {
            return '/setup';
          }
          return null;
        }

        // 2. Check if onboarding is shown
        if (!settingsViewModel.onboardingShown) {
          if (location != '/onboarding') {
            return '/onboarding';
          }
          return null;
        }

        // 3. Local mode - allow access to main app, block auth routes
        if (settingsViewModel.isLocalMode) {
          if (location == '/login' || location == '/register') {
            return '/';
          }
          return null;
        }

        // 4. Online mode - existing auth logic
        final isAuthenticated = authViewModel.isAuthenticated;
        final isAuthRoute = location == '/login' || location == '/register';

        if (authViewModel.state == AuthState.initial) {
          return null;
        }

        if (!isAuthenticated && !isAuthRoute) {
          return '/login';
        }

        if (isAuthenticated && isAuthRoute) {
          return '/';
        }

        return null;
      },
      refreshListenable: Listenable.merge([authViewModel, settingsViewModel]),
      routes: [
        GoRoute(
          path: '/setup',
          name: 'setup',
          builder: (context, state) => const SetupPage(),
        ),
        GoRoute(
          path: '/onboarding',
          name: 'onboarding',
          builder: (context, state) => const OnboardingPage(),
        ),
        GoRoute(
          path: '/login',
          name: 'login',
          builder: (context, state) => const LoginPage(),
        ),
        GoRoute(
          path: '/register',
          name: 'register',
          builder: (context, state) => const RegisterPage(),
        ),
        GoRoute(
          path: '/',
          name: 'daily',
          builder: (context, state) {
            final dateStr = state.uri.queryParameters['date'];
            return DailyAgendaPage(initialDate: dateStr);
          },
        ),
        GoRoute(
          path: '/calendar',
          name: 'calendar',
          builder: (context, state) => const CalendarPage(),
        ),
        GoRoute(
          path: '/task/new',
          name: 'task-new',
          builder: (context, state) {
            final dateStr = state.uri.queryParameters['date'];
            return TaskFormPage(initialDate: dateStr);
          },
        ),
        GoRoute(
          path: '/task/:id/edit',
          name: 'task-edit',
          builder: (context, state) {
            final taskId = state.pathParameters['id']!;
            return TaskFormPage(taskId: taskId);
          },
        ),
        GoRoute(
          path: '/settings',
          name: 'settings',
          builder: (context, state) => const SettingsPage(),
        ),
      ],
    );
  }
}
