import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/core/bottom_menu/bottom_menu.dart';
import 'package:kasy_kit/core/config/features.dart';
import 'package:kasy_kit/core/data/api/analytics_api.dart';
import 'package:kasy_kit/core/guards/user_info_guard.dart';
import 'package:kasy_kit/core/navigation/kasy_navigation_config.dart';
import 'package:kasy_kit/core/navigation/kasy_page_transition.dart';
import 'package:kasy_kit/core/security/biometric_guard.dart';
import 'package:kasy_kit/core/widgets/page_not_found.dart';
import 'package:kasy_kit/features/authentication/ui/phone_auth_page.dart';
import 'package:kasy_kit/features/authentication/ui/recover_password_page.dart';
import 'package:kasy_kit/features/authentication/ui/signin_page.dart';
import 'package:kasy_kit/features/authentication/ui/signup_page.dart';
import 'package:kasy_kit/features/feedbacks/ui/feedback_page.dart';
import 'package:kasy_kit/features/llm_chat/llm_chat_page.dart';
import 'package:kasy_kit/features/local_reminder/ui/reminder_page.dart';
import 'package:kasy_kit/features/onboarding/ui/onboarding_page.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/admin_home_widgets.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/admin_paywalls.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/admin_routes.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/send_push_notification_page.dart';
import 'package:kasy_kit/features/subscription/ui/component/premium_page_factory.dart';
import 'package:kasy_kit/features/subscription/ui/premium_page.dart';
import 'package:logger/logger.dart';

final goRouterProvider = Provider<GoRouter>((ref) => generateRouter());

extension GoRouterRiverpod on Ref {
  GoRouter get goRouter => read(goRouterProvider);
}

final navigatorKey = GlobalKey<NavigatorState>();

GoRouter generateRouter({
  String? initialLocation,
  List<GoRoute>? additionalRoutes,
  List<NavigatorObserver>? observers,
}) {
  return GoRouter(
    initialLocation: '/',
    navigatorKey: navigatorKey,
    // Catches unknown routes (e.g. an Android warm-start from the home widget
    // landed on a stale URI) and silently sends the user home instead of
    // surfacing a dead-end "404" page. We log the offending URI so a real
    // misconfigured route doesn't get masked.
    // Note: GoRouter doesn't accept both onException and errorBuilder, so the
    // /404 GoRoute below is what reaches PageNotFound when explicitly navigated.
    onException: (context, state, router) {
      Logger().w(
        'GoRouter caught unknown route → "${state.uri}" '
        '(matched: "${state.matchedLocation}", error: ${state.error}). '
        'Redirecting to "/".',
      );
      router.go('/');
    },
    observers: [
      AnalyticsObserver(analyticsApi: MixpanelAnalyticsApi.instance()),

      ...?observers,
    ],
    routes: [
      GoRoute(
        name: 'home',
        path: '/',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const UserInfosGuard(
            fallbackRoute: '/onboarding',
            child: BiometricGuard(child: BottomMenu()),
          ),
        ),
      ),
      GoRoute(
        name: 'onboarding',
        path: '/onboarding',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const OnboardingPage(),
        ),
      ),
      GoRoute(
        name: 'signup',
        path: '/signup',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          transition: KasyNavigationConfig.authPeer,
          child: const SignupPage(),
        ),
      ),
      GoRoute(
        name: 'signin',
        path: '/signin',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          transition: KasyNavigationConfig.authPeer,
          child: const SigninPage(),
        ),
      ),
      GoRoute(
        name: 'signinWithPhone',
        path: '/signinWithPhone',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const PhoneAuthPage(),
        ),
      ),
      if (withRevenuecat)
        GoRoute(
          name: 'premium',
          path: '/premium',
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const PremiumPage(paywall: PaywallFactory.minimal),
          ),
        ),
      if (withFeedback)
        GoRoute(
          name: 'feedback',
          path: '/feedback',
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const FeedbackPage(),
          ),
        ),
      if (withLlmChat)
        GoRoute(
          name: 'assistant',
          path: '/assistant',
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const LlmChatPage(),
          ),
        ),
      if (withLocalNotifications)
        GoRoute(
          name: 'reminder',
          path: '/reminder',
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const ReminderPage(),
          ),
        ),
      GoRoute(
        name: 'notifications',
        path: '/notifications',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const UserInfosGuard(
            fallbackRoute: '/onboarding',
            child: BiometricGuard(child: BottomMenu(initialRoute: 'notifications')),
          ),
        ),
      ),
      GoRoute(
        name: 'settings',
        path: '/settings',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const UserInfosGuard(
            fallbackRoute: '/onboarding',
            child: BiometricGuard(child: BottomMenu(initialRoute: 'settings')),
          ),
        ),
      ),
      GoRoute(
        name: 'recover_password',
        path: '/recover_password',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const RecoverPasswordPage(),
        ),
      ),
      if (kDebugMode) ...[
        GoRoute(
          name: 'admin_paywalls',
          path: adminRoutePaywalls,
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const AdminPaywalls(),
          ),
        ),
        GoRoute(
          name: 'admin_home_widgets',
          path: adminRouteHomeWidgets,
          pageBuilder: (context, state) => kasyTransitionPage(
            key: state.pageKey,
            child: const AdminHomeWidgets(),
          ),
        ),
        GoRoute(
          name: 'admin_premium_preview',
          path: '/admin/premium/:variant',
          pageBuilder: (context, state) {
            final paywall = paywallFactoryFromAdminRoute(
              state.pathParameters['variant'],
            );
            if (paywall == null || !withRevenuecat) {
              return kasyTransitionPage(
                key: state.pageKey,
                child: const PageNotFound(),
              );
            }
            return kasyTransitionPage(
              key: state.pageKey,
              child: PremiumPage(paywall: paywall),
            );
          },
        ),
      ],
      GoRoute(
        name: 'send_push',
        path: adminRouteSendPush,
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const SendPushNotificationPage(),
        ),
      ),
      GoRoute(
        name: '404',
        path: '/404',
        pageBuilder: (context, state) => kasyTransitionPage(
          key: state.pageKey,
          child: const PageNotFound(),
        ),
      ),
    ],
  );
}
