import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../../features/auth/presentation/bloc/auth_cubit.dart';
import '../../features/auth/presentation/bloc/auth_state.dart';
import '../../features/auth/presentation/screens/splash_screen.dart';
import '../../features/auth/presentation/screens/login_screen.dart';
import '../../features/auth/presentation/screens/register_screen.dart';
import '../../features/dashboard/presentation/screens/dashboard_screen.dart';
import '../../features/dashboard/presentation/screens/profile_screen.dart';
import '../../features/chat/presentation/screens/chat_screen.dart';
import '../../features/akinator/presentation/screens/akinator_screen.dart';
import '../../features/quiz/presentation/screens/quiz_setup_screen.dart';
import '../../features/generator/presentation/screens/generator_screen.dart';
import '../../features/generator/presentation/screens/generator_results_screen.dart';
import '../../features/generator/data/datasources/generator_remote_datasource.dart';
import '../../features/scenarios/presentation/screens/scenario_browser_screen.dart';
import '../../features/scenarios/presentation/screens/scenario_detail_screen.dart';
import '../../features/knowledge_base/presentation/screens/kb_list_screen.dart';
import '../../features/knowledge_base/presentation/screens/kb_upload_screen.dart';
import '../../features/leaderboard/presentation/screens/leaderboard_screen.dart';
import '../../shared/bottom_nav_shell.dart';
import '../../shared/more_menu_screen.dart';
import '../../shared/settings_screen.dart';

class AppRouter {
  final AuthCubit authCubit;
  late final GoRouter router;

  AppRouter(this.authCubit) {
    router = GoRouter(
      initialLocation: '/splash',
      refreshListenable: _GoRouterAuthRefresh(authCubit.stream),
      redirect: _redirect,
      routes: [
        GoRoute(
          path: '/splash',
          builder: (_, __) => const SplashScreen(),
        ),
        GoRoute(
          path: '/login',
          builder: (_, __) => const LoginScreen(),
        ),
        GoRoute(
          path: '/register',
          builder: (_, __) => const RegisterScreen(),
        ),
        StatefulShellRoute.indexedStack(
          builder: (_, __, navigationShell) =>
              BottomNavShell(navigationShell: navigationShell),
          branches: [
            // ── Tab 0: Home ──
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/app/dashboard',
                  builder: (_, __) => const DashboardScreen(),
                  routes: [
                    GoRoute(
                      path: 'profile',
                      builder: (_, __) => const ProfileScreen(),
                    ),
                  ],
                ),
              ],
            ),
            // ── Tab 1: Chat ──
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/app/chat',
                  builder: (_, __) => const ChatScreen(),
                ),
              ],
            ),
            // ── Tab 2: Akinator ──
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/app/akinator',
                  builder: (_, __) => const AkinatorScreen(),
                ),
              ],
            ),
            // ── Tab 3: Quiz ──
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/app/quiz',
                  builder: (_, __) => const QuizSetupScreen(),
                ),
              ],
            ),
            // ── Tab 4: More ──
            StatefulShellBranch(
              routes: [
                GoRoute(
                  path: '/app/more',
                  builder: (_, __) => const MoreMenuScreen(),
                  routes: [
                    // Scenarios
                    GoRoute(
                      path: 'scenarios',
                      builder: (_, __) => const ScenarioBrowserScreen(),
                      routes: [
                        GoRoute(
                          path: ':id',
                          builder: (_, state) {
                            final id = state.pathParameters['id']!;
                            return ScenarioDetailScreen(scenarioId: id);
                          },
                        ),
                      ],
                    ),
                    // Generator
                    GoRoute(
                      path: 'generator',
                      builder: (_, __) => const GeneratorScreen(),
                      routes: [
                        GoRoute(
                          path: 'results',
                          builder: (_, state) {
                            final result =
                                state.extra as GenerateResultModel;
                            return GeneratorResultsScreen(result: result);
                          },
                        ),
                      ],
                    ),
                    // Knowledge Base
                    GoRoute(
                      path: 'kb',
                      builder: (_, __) => const KBListScreen(),
                      routes: [
                        GoRoute(
                          path: 'upload',
                          builder: (_, __) => const KBUploadScreen(),
                        ),
                      ],
                    ),
                    // Leaderboard
                    GoRoute(
                      path: 'leaderboard',
                      builder: (_, __) => const LeaderboardScreen(),
                    ),
                    // Settings
                    GoRoute(
                      path: 'settings',
                      builder: (_, __) => const SettingsScreen(),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  String? _redirect(BuildContext context, GoRouterState state) {
    final authState = authCubit.state;
    final location = state.matchedLocation;

    final isSplash = location == '/splash';
    final isAuthScreen = location == '/login' || location == '/register';

    if (authState is AuthInitial || authState is AuthLoading) {
      return isSplash ? null : '/splash';
    }

    if (authState is Authenticated) {
      if (isSplash || isAuthScreen) return '/app/dashboard';
      return null;
    }

    if (isSplash || isAuthScreen) return null;
    return '/login';
  }
}

class _GoRouterAuthRefresh extends ChangeNotifier {
  late final StreamSubscription<dynamic> _sub;

  _GoRouterAuthRefresh(Stream<dynamic> stream) {
    _sub = stream.asBroadcastStream().listen((_) => notifyListeners());
  }

  @override
  void dispose() {
    _sub.cancel();
    super.dispose();
  }
}