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

import '../../features/auth/pages/login_page.dart';
import '../../features/home/pages/home_page.dart';
import '../../features/programs/pages/programs_page.dart';
import '../../features/program_detail/pages/program_detail_page.dart';
import '../../features/settings/pages/settings_page.dart';
import '../../features/home/pages/complete_page.dart';
import '../../features/auth/providers/auth_provider.dart';

final _authRefreshStream = AuthRefreshStream();

/// 应用路由配置
final goRouterProvider = Provider<GoRouter>((ref) {
  final authState = ref.watch(authProvider);

  // 监听认证状态变化，触发 GoRouter 重新评估 redirect
  ref.listen(authProvider, (prev, next) {
    _authRefreshStream.notify();
  });

  return GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      final isAuthenticated = authState.status == AuthStatus.authenticated;
      final isLoginPage = state.uri.path == '/login';

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

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

      return null;
    },
    refreshListenable: _authRefreshStream,
    routes: [
      GoRoute(
        path: '/login',
        name: 'login',
        builder: (context, state) => const LoginPage(),
      ),
      GoRoute(
        path: '/',
        name: 'home',
        builder: (context, state) {
          final tabParam = state.uri.queryParameters['tab'];
          final initialTab = int.tryParse(tabParam ?? '') ?? 0;
          return HomePage(initialTab: initialTab);
        },
      ),
      GoRoute(
        path: '/programs',
        name: 'programs',
        builder: (context, state) => const ProgramsPage(),
      ),
      GoRoute(
        path: '/programs/:id',
        name: 'programDetail',
        builder: (context, state) {
          final id = state.pathParameters['id'];
          return ProgramDetailPage(programId: id ?? '');
        },
      ),
      GoRoute(
        path: '/settings',
        name: 'settings',
        builder: (context, state) => const SettingsPage(),
      ),
      GoRoute(
        path: '/complete',
        name: 'complete',
        builder: (context, state) => const CompletePage(),
      ),
    ],
  );
});

/// 桥接 Riverpod 到 GoRouter 的 refreshListenable
class AuthRefreshStream extends ChangeNotifier {
  void notify() => notifyListeners();
}
