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

import '../features/auth/presentation/pages/splash_page.dart';
import '../features/auth/presentation/pages/guide_page.dart';
import '../features/auth/presentation/pages/onboarding_page.dart';
import '../features/auth/presentation/pages/backup_mnemonic_page.dart';
import '../features/auth/presentation/pages/verify_mnemonic_page.dart';
import '../features/auth/presentation/pages/wallet_created_page.dart';
import '../features/auth/presentation/pages/import_mnemonic_page.dart';
import '../features/auth/presentation/pages/phone_register_page.dart';
import '../features/auth/presentation/pages/phone_login_page.dart';
import '../features/auth/presentation/pages/forgot_password_page.dart';
import '../features/auth/presentation/pages/sms_verify_page.dart';
import '../features/auth/presentation/pages/set_password_page.dart';
import '../features/home/presentation/pages/home_shell_page.dart';
import '../features/ranking/presentation/pages/ranking_page.dart';
import '../features/mining/presentation/pages/mining_page.dart';
import '../features/trading/presentation/pages/trading_page.dart';
import '../features/trading/presentation/pages/ledger_detail_page.dart';
import '../features/profile/presentation/pages/profile_page.dart';
import '../features/profile/presentation/pages/edit_profile_page.dart';
import '../features/share/presentation/pages/share_page.dart';
import '../features/deposit/presentation/pages/deposit_usdt_page.dart';
import '../features/planting/presentation/pages/planting_quantity_page.dart';
import '../features/planting/presentation/pages/planting_location_page.dart';
import '../features/security/presentation/pages/google_auth_page.dart';
import '../features/security/presentation/pages/change_password_page.dart';
import '../features/security/presentation/pages/change_payment_password_page.dart'; // [2026-03-05] 支付密码页
import '../features/security/presentation/pages/reset_payment_password_page.dart';  // [2026-03-05] 忘记支付密码页
import '../features/security/presentation/pages/bind_email_page.dart';
import '../features/authorization/presentation/pages/authorization_apply_page.dart';
import '../features/withdraw/presentation/pages/withdraw_usdt_page.dart';
import '../features/withdraw/presentation/pages/withdraw_confirm_page.dart';
import '../features/withdraw/presentation/pages/withdraw_fiat_page.dart';
import '../features/withdraw/presentation/pages/withdraw_fiat_confirm_page.dart';
import '../features/notification/presentation/pages/notification_inbox_page.dart';
import '../features/account/presentation/pages/account_switch_page.dart';
import '../features/kyc/presentation/pages/kyc_entry_page.dart';
import '../features/kyc/presentation/pages/kyc_phone_page.dart';
import '../features/kyc/presentation/pages/kyc_id_page.dart';
import '../features/kyc/presentation/pages/kyc_face_page.dart';
import '../features/kyc/presentation/pages/kyc_id_card_page.dart';
import '../features/kyc/presentation/pages/change_phone_page.dart';
import '../features/contract_signing/presentation/pages/contract_signing_page.dart';
import '../features/contract_signing/presentation/pages/pending_contracts_page.dart';
import '../features/pending_actions/presentation/pages/pending_actions_page.dart';
// [2026-02-17] 新增：预种计划页面（1887 USDT/份，累计 10 份合成 1 棵树）
import '../features/pre_planting/presentation/pages/pre_planting_hub_page.dart';
import '../features/pre_planting/presentation/pages/pre_planting_purchase_page.dart';
import '../features/pre_planting/presentation/pages/pre_planting_position_page.dart';
import '../features/pre_planting/presentation/pages/pre_planting_merge_detail_page.dart';
import '../features/pre_planting/presentation/pages/pre_planting_merge_signing_page.dart';
// [2026-03-02] 纯新增：团队预种页面（功能6）
import '../features/pre_planting/presentation/pages/team_pre_planting_page.dart';
// [2026-02-19] 纯新增：树转让页面
import '../features/transfer/presentation/pages/transfer_list_page.dart';
import '../features/transfer/presentation/pages/transfer_detail_page.dart';
import '../features/transfer/presentation/pages/transfer_initiate_page.dart';
import 'route_paths.dart';
import 'route_names.dart';

/// 全局根导航 Key，用于在非 Widget 上下文中进行导航
final rootNavigatorKey = GlobalKey<NavigatorState>();
final _shellNavigatorKey = GlobalKey<NavigatorState>();

/// 备份助记词页面参数 (新版 - 只需要用户序列号)
class BackupMnemonicParams {
  final String userSerialNum;
  final String? referralCode;

  BackupMnemonicParams({
    required this.userSerialNum,
    this.referralCode,
  });
}

/// 确认备份页面参数
class VerifyMnemonicParams {
  final List<String> mnemonicWords;
  final String kavaAddress;
  final String dstAddress;
  final String bscAddress;
  final String userSerialNum;
  final String? referralCode;

  VerifyMnemonicParams({
    required this.mnemonicWords,
    required this.kavaAddress,
    required this.dstAddress,
    required this.bscAddress,
    required this.userSerialNum,
    this.referralCode,
  });
}

/// 创建成功页面参数
class WalletCreatedParams {
  final String kavaAddress;
  final String dstAddress;
  final String bscAddress;
  final String userSerialNum;
  final String? referralCode;

  WalletCreatedParams({
    required this.kavaAddress,
    required this.dstAddress,
    required this.bscAddress,
    required this.userSerialNum,
    this.referralCode,
  });
}

/// 分享页面参数
class SharePageParams {
  final String shareLink;
  final String? referralCode;

  SharePageParams({
    required this.shareLink,
    this.referralCode,
  });
}

final appRouterProvider = Provider<GoRouter>((ref) {
  return GoRouter(
    navigatorKey: rootNavigatorKey,
    initialLocation: RoutePaths.splash,
    debugLogDiagnostics: true,
    routes: [
      // Splash Screen
      GoRoute(
        path: RoutePaths.splash,
        name: RouteNames.splash,
        builder: (context, state) => const SplashPage(),
      ),

      // Guide Pages (向导页)
      GoRoute(
        path: RoutePaths.guide,
        name: RouteNames.guide,
        builder: (context, state) {
          // 支持传入初始页索引
          final initialPage = state.extra as int? ?? 0;
          return GuidePage(initialPage: initialPage);
        },
      ),

      // Onboarding / Create Account
      GoRoute(
        path: RoutePaths.onboarding,
        name: RouteNames.onboarding,
        builder: (context, state) => const OnboardingPage(),
      ),

      // Import Mnemonic (导入助记词)
      GoRoute(
        path: RoutePaths.importMnemonic,
        name: RouteNames.importMnemonic,
        builder: (context, state) => const ImportMnemonicPage(),
      ),

      // Phone Register (手机号注册)
      GoRoute(
        path: RoutePaths.phoneRegister,
        name: RouteNames.phoneRegister,
        builder: (context, state) {
          final params = state.extra as PhoneRegisterParams?;
          return PhoneRegisterPage(
            inviterReferralCode: params?.inviterReferralCode,
          );
        },
      ),

      // Phone Login (手机号+密码登录)
      GoRoute(
        path: RoutePaths.phoneLogin,
        name: RouteNames.phoneLogin,
        builder: (context, state) {
          return const PhoneLoginPage();
        },
      ),

      // Forgot Password (找回密码)
      GoRoute(
        path: RoutePaths.forgotPassword,
        name: RouteNames.forgotPassword,
        builder: (context, state) {
          return const ForgotPasswordPage();
        },
      ),

      // SMS Verify (短信验证码)
      GoRoute(
        path: RoutePaths.smsVerify,
        name: RouteNames.smsVerify,
        builder: (context, state) {
          final params = state.extra as SmsVerifyParams;
          return SmsVerifyPage(
            phoneNumber: params.phoneNumber,
            type: params.type,
            inviterReferralCode: params.inviterReferralCode,
          );
        },
      ),

      // Set Password (设置登录密码)
      GoRoute(
        path: RoutePaths.setPassword,
        name: RouteNames.setPassword,
        builder: (context, state) {
          final params = state.extra as SetPasswordParams;
          return SetPasswordPage(
            userSerialNum: params.userSerialNum,
            inviterReferralCode: params.inviterReferralCode,
            phoneNumber: params.phoneNumber,
            smsCode: params.smsCode,
            skipVerify: params.skipVerify,
          );
        },
      ),

      // Backup Mnemonic (备份助记词 - 会调用 API 获取钱包信息，已屏蔽)
      GoRoute(
        path: RoutePaths.backupMnemonic,
        name: RouteNames.backupMnemonic,
        builder: (context, state) {
          final params = state.extra as BackupMnemonicParams;
          return BackupMnemonicPage(
            userSerialNum: params.userSerialNum,
            referralCode: params.referralCode,
          );
        },
      ),

      // Verify Mnemonic (确认备份)
      GoRoute(
        path: RoutePaths.verifyMnemonic,
        name: RouteNames.verifyMnemonic,
        builder: (context, state) {
          final params = state.extra as VerifyMnemonicParams;
          return VerifyMnemonicPage(
            mnemonicWords: params.mnemonicWords,
            kavaAddress: params.kavaAddress,
            dstAddress: params.dstAddress,
            bscAddress: params.bscAddress,
            userSerialNum: params.userSerialNum,
            referralCode: params.referralCode,
          );
        },
      ),

      // Wallet Created (创建成功)
      GoRoute(
        path: RoutePaths.walletCreated,
        name: RouteNames.walletCreated,
        builder: (context, state) {
          final params = state.extra as WalletCreatedParams;
          return WalletCreatedPage(
            kavaAddress: params.kavaAddress,
            dstAddress: params.dstAddress,
            bscAddress: params.bscAddress,
            userSerialNum: params.userSerialNum,
            referralCode: params.referralCode,
          );
        },
      ),

      // Edit Profile (编辑资料)
      GoRoute(
        path: RoutePaths.editProfile,
        name: RouteNames.editProfile,
        builder: (context, state) => const EditProfilePage(),
      ),

      // Notification Inbox (通知中心)
      GoRoute(
        path: RoutePaths.notifications,
        name: RouteNames.notifications,
        builder: (context, state) => const NotificationInboxPage(),
      ),

      // Account Switch Page (账号切换)
      GoRoute(
        path: RoutePaths.accountSwitch,
        name: RouteNames.accountSwitch,
        builder: (context, state) => const AccountSwitchPage(),
      ),

      // Share Page (分享页面)
      GoRoute(
        path: RoutePaths.share,
        name: RouteNames.share,
        builder: (context, state) {
          final params = state.extra as SharePageParams;
          return SharePage(
            shareLink: params.shareLink,
            referralCode: params.referralCode,
          );
        },
      ),

      // Deposit USDT Page (充值 USDT)
      GoRoute(
        path: RoutePaths.depositUsdt,
        name: RouteNames.depositUsdt,
        builder: (context, state) => const DepositUsdtPage(),
      ),

      // Planting Quantity Page (认种 - 选择数量)
      GoRoute(
        path: RoutePaths.plantingQuantity,
        name: RouteNames.plantingQuantity,
        builder: (context, state) => const PlantingQuantityPage(),
      ),

      // Planting Location Page (认种 - 选择省市)
      GoRoute(
        path: RoutePaths.plantingLocation,
        name: RouteNames.plantingLocation,
        builder: (context, state) {
          final params = state.extra as PlantingLocationParams;
          return PlantingLocationPage(
            quantity: params.quantity,
            totalPrice: params.totalPrice,
            orderNo: params.orderNo,
          );
        },
      ),

      // Google Auth Page (谷歌验证器)
      GoRoute(
        path: RoutePaths.googleAuth,
        name: RouteNames.googleAuth,
        builder: (context, state) => const GoogleAuthPage(),
      ),

      // Change Password Page (修改密码)
      GoRoute(
        path: RoutePaths.changePassword,
        name: RouteNames.changePassword,
        builder: (context, state) => const ChangePasswordPage(),
      ),

      // Payment Password Page (支付密码设置/修改) [2026-03-05]
      GoRoute(
        path: RoutePaths.paymentPassword,
        name: RouteNames.paymentPassword,
        builder: (context, state) => const ChangePaymentPasswordPage(),
      ),

      // Reset Payment Password Page (忘记支付密码) [2026-03-05]
      GoRoute(
        path: RoutePaths.resetPaymentPassword,
        name: RouteNames.resetPaymentPassword,
        builder: (context, state) => const ResetPaymentPasswordPage(),
      ),

      // Bind Email Page (绑定邮箱)
      GoRoute(
        path: RoutePaths.bindEmail,
        name: RouteNames.bindEmail,
        builder: (context, state) => const BindEmailPage(),
      ),

      // Authorization Apply Page (自助申请授权)
      GoRoute(
        path: RoutePaths.authorizationApply,
        name: RouteNames.authorizationApply,
        builder: (context, state) => const AuthorizationApplyPage(),
      ),

      // Ledger Detail Page (账本明细)
      GoRoute(
        path: RoutePaths.ledgerDetail,
        name: RouteNames.ledgerDetail,
        builder: (context, state) => const LedgerDetailPage(),
      ),

      // Withdraw USDT Page (USDT 提款)
      GoRoute(
        path: RoutePaths.withdrawUsdt,
        name: RouteNames.withdrawUsdt,
        builder: (context, state) => const WithdrawUsdtPage(),
      ),

      // Withdraw Confirm Page (提款确认)
      GoRoute(
        path: RoutePaths.withdrawConfirm,
        name: RouteNames.withdrawConfirm,
        builder: (context, state) {
          final params = state.extra as WithdrawUsdtParams;
          return WithdrawConfirmPage(params: params);
        },
      ),

      // Withdraw Fiat Page (法币提现)
      GoRoute(
        path: RoutePaths.withdrawFiat,
        name: RouteNames.withdrawFiat,
        builder: (context, state) => const WithdrawFiatPage(),
      ),

      // Withdraw Fiat Confirm Page (法币提现确认)
      GoRoute(
        path: RoutePaths.withdrawFiatConfirm,
        name: RouteNames.withdrawFiatConfirm,
        builder: (context, state) {
          final params = state.extra as WithdrawFiatParams;
          return WithdrawFiatConfirmPage(params: params);
        },
      ),

      // KYC Entry Page (实名认证入口)
      GoRoute(
        path: RoutePaths.kycEntry,
        name: RouteNames.kycEntry,
        builder: (context, state) {
          // 从认种流程来时会带 orderNo
          final orderNo = state.extra as String?;
          return KycEntryPage(orderNo: orderNo);
        },
      ),

      // KYC Phone Verification Page (手机号验证)
      GoRoute(
        path: RoutePaths.kycPhone,
        name: RouteNames.kycPhone,
        builder: (context, state) => const KycPhonePage(),
      ),

      // KYC ID Verification Page (层级1: 实名认证 - 二要素)
      GoRoute(
        path: RoutePaths.kycId,
        name: RouteNames.kycId,
        builder: (context, state) {
          // 从认种流程来时会带 orderNo
          final orderNo = state.extra as String?;
          return KycIdPage(orderNo: orderNo);
        },
      ),

      // KYC Face Verification Page (层级2: 实人认证 - 人脸活体)
      GoRoute(
        path: RoutePaths.kycFace,
        name: RouteNames.kycFace,
        builder: (context, state) => const KycFacePage(),
      ),

      // KYC ID Card Upload Page (层级3: KYC - 证件照上传)
      GoRoute(
        path: RoutePaths.kycIdCard,
        name: RouteNames.kycIdCard,
        builder: (context, state) => const KycIdCardPage(),
      ),

      // Change Phone Page (更换手机号)
      GoRoute(
        path: RoutePaths.changePhone,
        name: RouteNames.changePhone,
        builder: (context, state) => const ChangePhonePage(),
      ),

      // [2026-03-04] Pre-Planting Hub Page (预种计划 - 入口汇总)
      GoRoute(
        path: RoutePaths.prePlantingHub,
        name: RouteNames.prePlantingHub,
        builder: (context, state) => const PrePlantingHubPage(),
      ),

      // [2026-02-17] Pre-Planting Purchase Page (预种计划 - 购买页)
      GoRoute(
        path: RoutePaths.prePlantingPurchase,
        name: RouteNames.prePlantingPurchase,
        builder: (context, state) => const PrePlantingPurchasePage(),
      ),

      // [2026-02-17] Pre-Planting Position Page (预种计划 - 持仓页)
      GoRoute(
        path: RoutePaths.prePlantingPosition,
        name: RouteNames.prePlantingPosition,
        builder: (context, state) => const PrePlantingPositionPage(),
      ),

      // [2026-02-17] Pre-Planting Merge Detail Page (预种计划 - 合并详情)
      GoRoute(
        path: '${RoutePaths.prePlantingMergeDetail}/:mergeNo',
        name: RouteNames.prePlantingMergeDetail,
        builder: (context, state) {
          final mergeNo = state.pathParameters['mergeNo'] ?? '';
          return PrePlantingMergeDetailPage(mergeNo: mergeNo);
        },
      ),

      // [2026-02-28] Pre-Planting Merge Signing Page (预种计划 - 合并合同签署)
      GoRoute(
        path: '${RoutePaths.prePlantingMergeSigning}/:mergeNo',
        name: RouteNames.prePlantingMergeSigning,
        builder: (context, state) {
          final mergeNo = state.pathParameters['mergeNo'] ?? '';
          return PrePlantingMergeSigningPage(mergeNo: mergeNo);
        },
      ),

      // [2026-03-02] Team Pre-Planting Page (团队预种 - 功能6)
      GoRoute(
        path: RoutePaths.teamPrePlanting,
        name: RouteNames.teamPrePlanting,
        builder: (context, state) => const TeamPrePlantingPage(),
      ),

      // [2026-02-19] Transfer List Page (树转让 - 记录列表)
      GoRoute(
        path: RoutePaths.transferList,
        name: RouteNames.transferList,
        builder: (context, state) => const TransferListPage(),
      ),

      // [2026-02-19] Transfer Detail Page (树转让 - 详情)
      GoRoute(
        path: '${RoutePaths.transferDetail}/:transferOrderNo',
        name: RouteNames.transferDetail,
        builder: (context, state) {
          final transferOrderNo = state.pathParameters['transferOrderNo'] ?? '';
          return TransferDetailPage(transferOrderNo: transferOrderNo);
        },
      ),

      // [2026-02-19] Transfer Initiate Page (树转让 - 发起)
      GoRoute(
        path: RoutePaths.transferInitiate,
        name: RouteNames.transferInitiate,
        builder: (context, state) => const TransferInitiatePage(),
      ),

      // Pending Contracts Page (待签署合同列表)
      // 注意：必须放在 contractSigning/:orderNo 前面，否则 "pending" 会被当成 orderNo
      GoRoute(
        path: RoutePaths.pendingContracts,
        name: RouteNames.pendingContracts,
        builder: (context, state) {
          final forceSign = state.extra as bool? ?? false;
          return PendingContractsPage(forceSign: forceSign);
        },
      ),

      // Contract Signing Page (合同签署)
      GoRoute(
        path: '${RoutePaths.contractSigning}/:orderNo',
        name: RouteNames.contractSigning,
        builder: (context, state) {
          final orderNo = state.pathParameters['orderNo'] ?? '';
          return ContractSigningPage(orderNo: orderNo);
        },
      ),

      // Pending Actions Page (待办操作)
      GoRoute(
        path: RoutePaths.pendingActions,
        name: RouteNames.pendingActions,
        builder: (context, state) => const PendingActionsPage(),
      ),

      // Main Shell with Bottom Navigation
      ShellRoute(
        navigatorKey: _shellNavigatorKey,
        builder: (context, state, child) => HomeShellPage(child: child),
        routes: [
          // Ranking Tab
          GoRoute(
            path: RoutePaths.ranking,
            name: RouteNames.ranking,
            pageBuilder: (context, state) => const NoTransitionPage(
              child: RankingPage(),
            ),
          ),

          // Mining Tab
          GoRoute(
            path: RoutePaths.mining,
            name: RouteNames.mining,
            pageBuilder: (context, state) => const NoTransitionPage(
              child: MiningPage(),
            ),
          ),

          // Trading Tab
          GoRoute(
            path: RoutePaths.trading,
            name: RouteNames.trading,
            pageBuilder: (context, state) => const NoTransitionPage(
              child: TradingPage(),
            ),
          ),

          // Profile Tab
          GoRoute(
            path: RoutePaths.profile,
            name: RouteNames.profile,
            pageBuilder: (context, state) => const NoTransitionPage(
              child: ProfilePage(),
            ),
          ),
        ],
      ),
    ],
  );
});
