import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/multi_account_service.dart';
import '../../../../core/providers/notification_badge_provider.dart';
import '../../../../core/telemetry/telemetry_service.dart';
import '../../../auth/presentation/providers/auth_provider.dart';
import '../../../auth/presentation/providers/wallet_status_provider.dart';
import '../../../../routes/route_paths.dart';

/// 账号切换页面
/// 显示所有已登录的账号列表，支持切换和添加新账号
class AccountSwitchPage extends ConsumerStatefulWidget {
  const AccountSwitchPage({super.key});

  @override
  ConsumerState<AccountSwitchPage> createState() => _AccountSwitchPageState();
}

class _AccountSwitchPageState extends ConsumerState<AccountSwitchPage> {
  List<AccountSummary> _accounts = [];
  String? _currentAccountId;
  bool _isLoading = true;
  bool _isSwitching = false;
  bool _isAddingAccount = false;

  @override
  void initState() {
    super.initState();
    _loadAccounts();
  }

  static const String _tag = '[AccountSwitchPage]';

  Future<void> _loadAccounts() async {
    debugPrint('$_tag _loadAccounts() - 开始加载账号列表');
    setState(() => _isLoading = true);

    final multiAccountService = ref.read(multiAccountServiceProvider);

    // 先执行迁移（如果需要）
    await multiAccountService.migrateFromSingleAccount();

    final accounts = await multiAccountService.getAccountList();
    final currentId = await multiAccountService.getCurrentAccountId();

    debugPrint('$_tag _loadAccounts() - 加载完成: ${accounts.length} 个账号, 当前=$currentId');

    if (mounted) {
      setState(() {
        _accounts = accounts;
        _currentAccountId = currentId;
        _isLoading = false;
      });
    }
  }

  Future<void> _switchToAccount(AccountSummary account) async {
    if (account.userSerialNum == _currentAccountId) {
      debugPrint('$_tag _switchToAccount() - 已是当前账号 ${account.userSerialNum}，直接返回');
      context.pop();
      return;
    }

    debugPrint('$_tag ========== 开始切换账号 ==========');
    debugPrint('$_tag 当前账号: $_currentAccountId');
    debugPrint('$_tag 目标账号: ${account.userSerialNum} (${account.username})');
    setState(() => _isSwitching = true);

    try {
      final multiAccountService = ref.read(multiAccountServiceProvider);

      // ===== [1/6] 停止所有用户相关的定时任务（必须在 switchToAccount 之前！）=====
      // 原因：switchToAccount 内部 saveCurrentAccountData() 需要 ~7 秒，
      // 如果定时器还在跑，save 期间发出的 API 请求在 clear 阶段 token 被删除后收到 401，
      // 触发 tokenExpired → logoutCurrentAccount() 把恢复中的数据清掉。
      // 在这里提前停止，确保 save 期间不会有新的 API 请求发出。
      debugPrint('$_tag [1/6] 停止全部定时器（在 switchToAccount 之前）...');
      ref.read(walletStatusProvider.notifier).stopPolling();
      debugPrint('$_tag   ✓ walletStatusProvider 轮询已停止');
      ref.read(pendingActionPollingServiceProvider).stop();
      debugPrint('$_tag   ✓ pendingActionPollingService 已停止');
      ref.read(notificationBadgeProvider.notifier).stopAutoRefresh();
      debugPrint('$_tag   ✓ notificationBadgeProvider 自动刷新已停止');
      if (TelemetryService().isInitialized) {
        await TelemetryService().pauseForLogout();
        debugPrint('$_tag   ✓ TelemetryService 已暂停');
      }
      debugPrint('$_tag [1/6] 定时器全部停止');

      // ===== [2/6] 调用 switchToAccount() =====
      // 内部流程：save → clear → restore → 设置当前账号
      // isSwitchingAccount 标志位会在整个过程中为 true，阻止 tokenExpired 事件
      debugPrint('$_tag [2/6] 调用 switchToAccount()...');
      final success = await multiAccountService.switchToAccount(
        account.userSerialNum,
      );

      if (success && mounted) {
        // ===== invalidate 所有账号相关 Provider（此时 storage 已是新账号数据）=====
        // 必须在 switchToAccount 返回后执行，确保 storage 已完整恢复，
        // Provider 重建时读到的是新账号数据
        debugPrint('$_tag [3/6] switchToAccount 成功，invalidate Provider...');
        ref.invalidate(authProvider);
        debugPrint('$_tag   ✓ authProvider invalidated');
        ref.invalidate(walletStatusProvider);
        debugPrint('$_tag   ✓ walletStatusProvider invalidated');
        ref.invalidate(notificationBadgeProvider);
        debugPrint('$_tag   ✓ notificationBadgeProvider invalidated（将重建并自动重启定时器）');

        // ===== 重新加载 auth 状态（从 SecureStorage 读取新账号数据）=====
        // invalidate 后 AuthNotifier 重建，初始状态是 AuthStatus.initial（未认证）
        // 必须主动调用 loadAuthState() 从 storage 读取新账号数据，否则 auth 状态为 initial，
        // 会导致依赖 auth 状态的组件认为用户未登录
        debugPrint('$_tag [4/6] 重新加载 auth 状态（从 storage 读取新账号数据）...');
        await ref.read(authProvider.notifier).loadAuthState();
        final newAuthState = ref.read(authProvider);
        debugPrint('$_tag   ✓ auth 状态已加载: status=${newAuthState.status}, userSerialNum=${newAuthState.userSerialNum}');
        // 重置 ApiClient 的 token 过期标记，确保新账号的请求不会被旧的过期标记阻塞
        ref.read(apiClientProvider).resetTokenExpiredFlag();
        debugPrint('$_tag   ✓ ApiClient tokenExpired 标记已重置');

        // ===== 恢复遥测上传（新账号上下文）=====
        debugPrint('$_tag [5/6] 恢复遥测上传...');
        if (TelemetryService().isInitialized) {
          TelemetryService().resumeAfterLogin();
          debugPrint('$_tag   ✓ TelemetryService 已恢复');
        }

        // 切换成功，跳转到主页刷新状态
        debugPrint('$_tag [6/6] 导航到 ranking 页面');
        debugPrint('$_tag ========== 切换账号完成 ==========');
        context.go(RoutePaths.ranking);
      } else if (mounted) {
        debugPrint('$_tag switchToAccount 返回 false，切换失败');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('切换账号失败')),
        );
      }
    } catch (e) {
      debugPrint('$_tag 切换账号异常: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('切换账号失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isSwitching = false);
      }
    }
  }

  Future<void> _addNewAccount() async {
    if (_isAddingAccount) return;

    debugPrint('$_tag ========== 开始添加新账号 ==========');
    debugPrint('$_tag 当前账号: $_currentAccountId');
    setState(() => _isAddingAccount = true);

    try {
      final multiAccountService = ref.read(multiAccountServiceProvider);

      // 保存当前账号数据
      debugPrint('$_tag [1/5] 保存当前账号数据...');
      await multiAccountService.saveCurrentAccountData();

      // ===== 1. 停止所有用户相关的定时任务 =====
      debugPrint('$_tag [2/6] 停止定时器...');
      ref.read(walletStatusProvider.notifier).stopPolling();
      debugPrint('$_tag   ✓ walletStatusProvider 轮询已停止');
      ref.read(pendingActionPollingServiceProvider).stop();
      debugPrint('$_tag   ✓ pendingActionPollingService 已停止');

      // 退出当前账号但保留数据
      debugPrint('$_tag [3/5] 调用 logoutCurrentAccount()...');
      await multiAccountService.logoutCurrentAccount();

      // ===== 2. invalidate 所有账号相关 Provider =====
      debugPrint('$_tag [4/5] invalidate Provider...');
      ref.invalidate(authProvider);
      debugPrint('$_tag   ✓ authProvider invalidated');
      ref.invalidate(walletStatusProvider);
      debugPrint('$_tag   ✓ walletStatusProvider invalidated');
      ref.invalidate(notificationBadgeProvider);
      debugPrint('$_tag   ✓ notificationBadgeProvider invalidated');

      // 跳转到向导页创建新账号
      debugPrint('$_tag [5/5] 导航到 guide 页面');
      debugPrint('$_tag ========== 添加新账号准备完成 ==========');
      if (mounted) {
        context.go(RoutePaths.guide);
      }
    } catch (e) {
      debugPrint('$_tag 添加新账号异常: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('添加新账号失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isAddingAccount = false);
      }
    }
  }

  Future<void> _deleteAccount(AccountSummary account) async {
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除账号'),
        content: Text('确定要删除账号 "${account.username}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFE57373),
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    debugPrint('$_tag ========== 开始删除账号 ==========');
    debugPrint('$_tag 删除目标: ${account.userSerialNum} (${account.username})');

    try {
      final multiAccountService = ref.read(multiAccountServiceProvider);
      await multiAccountService.deleteAccount(account.userSerialNum);
      debugPrint('$_tag 账号已从存储中删除');

      // 重新加载账号列表
      await _loadAccounts();
      debugPrint('$_tag 账号列表已刷新，剩余 ${_accounts.length} 个账号');

      // 如果没有账号了，跳转到向导页
      if (_accounts.isEmpty && mounted) {
        debugPrint('$_tag 无剩余账号，导航到 guide 页面');
        context.go(RoutePaths.guide);
      }
      debugPrint('$_tag ========== 删除账号完成 ==========');
    } catch (e) {
      debugPrint('$_tag 删除账号异常: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除账号失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFFBF5),
      appBar: AppBar(
        backgroundColor: const Color(0xFFFFFBF5),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF5D4037)),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          '切换账号',
          style: TextStyle(
            fontSize: 18,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(
                color: Color(0xFFD4AF37),
              ),
            )
          : (_isSwitching || _isAddingAccount)
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const CircularProgressIndicator(
                        color: Color(0xFFD4AF37),
                      ),
                      const SizedBox(height: 16),
                      Text(
                        _isAddingAccount ? '正在准备...' : '正在切换账号...',
                        style: const TextStyle(
                          fontSize: 14,
                          color: Color(0xFF5D4037),
                        ),
                      ),
                    ],
                  ),
                )
              : ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    // 账号列表标题
                    const Padding(
                      padding: EdgeInsets.only(bottom: 12),
                      child: Text(
                        '已登录的账号',
                        style: TextStyle(
                          fontSize: 14,
                          fontFamily: 'Inter',
                          fontWeight: FontWeight.w500,
                          color: Color(0x995D4037),
                        ),
                      ),
                    ),
                    // 账号列表
                    ..._accounts.map((account) => _buildAccountItem(account)),
                    const SizedBox(height: 16),
                    // 添加新账号按钮
                    _buildAddAccountButton(),
                  ],
                ),
    );
  }

  Widget _buildAccountItem(AccountSummary account) {
    final isCurrent = account.userSerialNum == _currentAccountId;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: isCurrent ? const Color(0xFFD4AF37).withValues(alpha: 0.1) : const Color(0xFFFFF5E6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: isCurrent ? const Color(0xFFD4AF37) : const Color(0x33D4AF37),
          width: isCurrent ? 2 : 1,
        ),
      ),
      child: InkWell(
        onTap: () => _switchToAccount(account),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              // 头像
              _buildAvatar(account),
              const SizedBox(width: 12),
              // 账号信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Flexible(
                          child: FittedBox(
                            fit: BoxFit.scaleDown,
                            alignment: Alignment.centerLeft,
                            child: Text(
                              account.username,
                              style: const TextStyle(
                                fontSize: 16,
                                fontFamily: 'Inter',
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF5D4037),
                              ),
                            ),
                          ),
                        ),
                        if (isCurrent) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: const Color(0xFFD4AF37),
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: const Text(
                              '当前',
                              style: TextStyle(
                                fontSize: 10,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 4),
                    FittedBox(
                      fit: BoxFit.scaleDown,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        account.userSerialNum,
                        style: const TextStyle(
                          fontSize: 12,
                          fontFamily: 'Inter',
                          color: Color(0x995D4037),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              // 删除按钮（非当前账号才显示）
              if (!isCurrent)
                IconButton(
                  icon: const Icon(
                    Icons.delete_outline,
                    color: Color(0xFFE57373),
                    size: 20,
                  ),
                  onPressed: () => _deleteAccount(account),
                ),
              // 当前账号显示勾选图标
              if (isCurrent)
                const Icon(
                  Icons.check_circle,
                  color: Color(0xFFD4AF37),
                  size: 24,
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAvatar(AccountSummary account) {
    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24),
        color: const Color(0xFFE8D5B7),
      ),
      clipBehavior: Clip.antiAlias,
      child: account.avatarSvg != null
          ? SvgPicture.string(
              account.avatarSvg!,
              fit: BoxFit.cover,
            )
          : const Icon(
              Icons.person,
              size: 28,
              color: Color(0xFF8B5A2B),
            ),
    );
  }

  Widget _buildAddAccountButton() {
    return GestureDetector(
      onTap: _addNewAccount,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: const Color(0xFFFFF5E6),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: const Color(0x33D4AF37),
            width: 1,
            style: BorderStyle.solid,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: const Color(0xFFD4AF37).withValues(alpha: 0.2),
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Icon(
                Icons.add,
                size: 20,
                color: Color(0xFFD4AF37),
              ),
            ),
            const SizedBox(width: 12),
            const Text(
              '添加新账号',
              style: TextStyle(
                fontSize: 15,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                color: Color(0xFF5D4037),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
