import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../presentation/pages/splash/splash_page.dart';
import '../../presentation/pages/auth/login_page.dart';
import '../../presentation/pages/auth/register_page.dart';
import '../../presentation/pages/auth/forgot_password_page.dart';
import '../../presentation/pages/auth/change_password_page.dart';
import '../../presentation/pages/auth/trade_password_page.dart';
import '../../presentation/pages/contribution/contribution_page.dart';
import '../../presentation/pages/contribution/contribution_records_page.dart';
import '../../presentation/pages/trading/trading_page.dart';
import '../../presentation/pages/asset/asset_page.dart';
import '../../presentation/pages/profile/profile_page.dart';
import '../../presentation/pages/profile/edit_profile_page.dart';
import '../../presentation/pages/profile/mining_records_page.dart';
import '../../presentation/pages/profile/batch_mining_records_page.dart';
import '../../presentation/pages/profile/planting_records_page.dart';
import '../../presentation/pages/asset/send_shares_page.dart';
import '../../presentation/pages/asset/receive_shares_page.dart';
import '../../presentation/pages/c2c/c2c_market_page.dart';
import '../../presentation/pages/c2c/c2c_publish_page.dart';
import '../../presentation/pages/c2c/c2c_order_detail_page.dart';
import '../../presentation/pages/profile/team_page.dart';
import '../../presentation/pages/profile/trading_records_page.dart';
import '../../presentation/pages/trading/transfer_records_page.dart';
import '../../presentation/pages/asset/p2p_transfer_records_page.dart';
import '../../presentation/pages/profile/help_center_page.dart';
import '../../presentation/pages/profile/about_page.dart';
import '../../presentation/pages/profile/notification_inbox_page.dart';
import '../../presentation/widgets/main_shell.dart';
import '../../presentation/providers/user_providers.dart';
import 'routes.dart';
import 'telemetry_route_observer.dart';

/// 不需要登录就能访问的公开路由
const _publicRoutes = {
  Routes.splash,
  Routes.login,
  Routes.register,
  Routes.forgotPassword,
};

/// 路由刷新通知器，用于在登录状态变化时刷新路由
class AuthNotifier extends ChangeNotifier {
  bool _isLoggedIn = false;

  bool get isLoggedIn => _isLoggedIn;

  void updateLoginState(bool isLoggedIn) {
    if (_isLoggedIn != isLoggedIn) {
      _isLoggedIn = isLoggedIn;
      // 使用 Future.microtask 延迟通知，避免在 provider rebuild 期间触发
      Future.microtask(() => notifyListeners());
    }
  }
}

final authNotifierProvider = ChangeNotifierProvider<AuthNotifier>((ref) {
  final authNotifier = AuthNotifier();

  // 监听用户登录状态变化
  ref.listen<bool>(isLoggedInProvider, (previous, next) {
    authNotifier.updateLoginState(next);
  });

  return authNotifier;
});

final appRouterProvider = Provider<GoRouter>((ref) {
  final authNotifier = ref.watch(authNotifierProvider);

  return GoRouter(
    initialLocation: Routes.splash,
    refreshListenable: authNotifier,
    observers: [TelemetryRouteObserver()],
    redirect: (context, state) {
      // 使用 authNotifier 中缓存的状态，而不是 ref.read
      final isLoggedIn = authNotifier.isLoggedIn;
      final currentPath = state.uri.path;

      // splash 页面不做重定向，让它自己处理初始化逻辑
      if (currentPath == Routes.splash) {
        return null;
      }

      // 未登录且访问受保护路由，重定向到登录页
      if (!isLoggedIn && !_publicRoutes.contains(currentPath)) {
        return Routes.login;
      }

      // 已登录且访问登录页，重定向到兑换页
      if (isLoggedIn && currentPath == Routes.login) {
        return Routes.trading;
      }

      return null;
    },
    routes: [
      GoRoute(
        path: Routes.splash,
        builder: (context, state) => const SplashPage(),
      ),
      GoRoute(
        path: Routes.login,
        builder: (context, state) => const LoginPage(),
      ),
      GoRoute(
        path: Routes.register,
        builder: (context, state) => const RegisterPage(),
      ),
      GoRoute(
        path: Routes.forgotPassword,
        builder: (context, state) => const ForgotPasswordPage(),
      ),
      GoRoute(
        path: Routes.changePassword,
        builder: (context, state) => const ChangePasswordPage(),
      ),
      GoRoute(
        path: Routes.tradePassword,
        builder: (context, state) => const TradePasswordPage(),
      ),
      GoRoute(
        path: Routes.contributionRecords,
        builder: (context, state) => const ContributionRecordsListPage(),
      ),
      GoRoute(
        path: Routes.miningRecords,
        builder: (context, state) => const MiningRecordsListPage(),
      ),
      GoRoute(
        path: Routes.batchMiningRecords,
        builder: (context, state) => const BatchMiningRecordsListPage(),
      ),
      GoRoute(
        path: Routes.plantingRecords,
        builder: (context, state) => const PlantingRecordsPage(),
      ),
      GoRoute(
        path: Routes.editProfile,
        builder: (context, state) => const EditProfilePage(),
      ),
      GoRoute(
        path: Routes.sendShares,
        builder: (context, state) => const SendSharesPage(),
      ),
      GoRoute(
        path: Routes.receiveShares,
        builder: (context, state) => const ReceiveSharesPage(),
      ),
      GoRoute(
        path: Routes.c2cMarket,
        builder: (context, state) => const C2cMarketPage(),
      ),
      GoRoute(
        path: Routes.c2cPublish,
        builder: (context, state) => const C2cPublishPage(),
      ),
      GoRoute(
        path: Routes.c2cOrderDetail,
        builder: (context, state) {
          final orderNo = state.extra as String;
          return C2cOrderDetailPage(orderNo: orderNo);
        },
      ),
      GoRoute(
        path: Routes.myTeam,
        builder: (context, state) => const TeamPage(),
      ),
      GoRoute(
        path: Routes.tradingRecords,
        builder: (context, state) => const TradingRecordsPage(),
      ),
      GoRoute(
        path: Routes.transferRecords,
        builder: (context, state) => const TransferRecordsPage(),
      ),
      GoRoute(
        path: Routes.p2pTransferRecords,
        builder: (context, state) => P2pTransferRecordsPage(
          filterDirection: state.uri.queryParameters['filter'],
        ),
      ),
      GoRoute(
        path: Routes.notifications,
        builder: (context, state) => const NotificationInboxPage(),
      ),
      GoRoute(
        path: Routes.helpCenter,
        builder: (context, state) => const HelpCenterPage(),
      ),
      GoRoute(
        path: Routes.about,
        builder: (context, state) => const AboutPage(),
      ),
      ShellRoute(
        builder: (context, state, child) => MainShell(child: child),
        routes: [
          GoRoute(
            path: Routes.contribution,
            builder: (context, state) => const ContributionPage(),
          ),
          GoRoute(
            path: Routes.trading,
            builder: (context, state) => const TradingPage(),
          ),
          GoRoute(
            path: Routes.asset,
            builder: (context, state) => const AssetPage(),
          ),
          GoRoute(
            path: Routes.profile,
            builder: (context, state) => const ProfilePage(),
          ),
        ],
      ),
    ],
  );
});
