import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/pending_action_service.dart';
import '../../../../core/services/contract_signing_service.dart';
import '../../../../core/services/reward_service.dart';
import '../../../../core/services/planting_service.dart';
import '../../../../routes/route_paths.dart';
import '../../../kyc/data/kyc_service.dart';
import 'special_deduction_page.dart';

/// 待办操作页面
/// 强制用户按后端配置执行待办任务，不可跳过
class PendingActionsPage extends ConsumerStatefulWidget {
  const PendingActionsPage({super.key});

  @override
  ConsumerState<PendingActionsPage> createState() => _PendingActionsPageState();
}

class _PendingActionsPageState extends ConsumerState<PendingActionsPage> {
  List<PendingAction> _pendingActions = [];
  int _currentIndex = 0;
  bool _isLoading = true;
  bool _isExecuting = false;
  String? _errorMessage;

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

  /// 加载待办操作列表
  Future<void> _loadPendingActions() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final service = ref.read(pendingActionServiceProvider);
      final response = await service.getMyPendingActions();

      setState(() {
        _pendingActions = response.pendingActionsSorted;
        _isLoading = false;
      });

      // 如果没有待办操作，直接完成
      if (_pendingActions.isEmpty) {
        _completeAllActions();
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '加载失败: $e';
      });
    }
  }

  /// 执行当前待办操作
  Future<void> _executeCurrentAction() async {
    debugPrint('[PendingActionsPage] _executeCurrentAction: 开始执行, currentIndex=$_currentIndex, total=${_pendingActions.length}');
    if (_currentIndex >= _pendingActions.length) {
      debugPrint('[PendingActionsPage] _executeCurrentAction: 已完成所有操作，跳转');
      _completeAllActions();
      return;
    }

    final action = _pendingActions[_currentIndex];
    debugPrint('[PendingActionsPage] _executeCurrentAction: 执行操作 ${action.actionCode} (id=${action.id})');
    setState(() => _isExecuting = true);

    try {
      // 根据不同的操作类型执行不同的逻辑
      final result = await _executeAction(action);
      debugPrint('[PendingActionsPage] _executeCurrentAction: _executeAction 返回 $result');

      if (result) {
        // 操作执行成功，标记为完成
        debugPrint('[PendingActionsPage] _executeCurrentAction: 调用后端 completeAction');
        final service = ref.read(pendingActionServiceProvider);
        await service.completeAction(action.id);
        debugPrint('[PendingActionsPage] _executeCurrentAction: completeAction 成功');

        // 移动到下一个操作
        setState(() {
          _currentIndex++;
          _isExecuting = false;
        });
        debugPrint('[PendingActionsPage] _executeCurrentAction: 移动到下一个操作, currentIndex=$_currentIndex');

        // 检查是否所有操作都完成
        if (_currentIndex >= _pendingActions.length) {
          debugPrint('[PendingActionsPage] _executeCurrentAction: 所有操作完成，跳转');
          _completeAllActions();
        } else {
          debugPrint('[PendingActionsPage] _executeCurrentAction: 还有 ${_pendingActions.length - _currentIndex} 个待办操作');
        }
      } else {
        // 用户取消或操作失败，保持在当前操作
        debugPrint('[PendingActionsPage] _executeCurrentAction: 操作未完成(result=false)，保持当前操作');
        setState(() => _isExecuting = false);
      }
    } catch (e) {
      debugPrint('[PendingActionsPage] _executeCurrentAction: 发生异常: $e');
      setState(() {
        _isExecuting = false;
        _errorMessage = '操作失败: $e';
      });
    }
  }

  /// 执行具体的操作，返回 true 表示成功
  /// 会先检查操作是否已经完成，如果已完成则直接返回 true
  Future<bool> _executeAction(PendingAction action) async {
    // 预检查：检查操作是否已经完成
    final alreadyCompleted = await _checkIfAlreadyCompleted(action);
    if (alreadyCompleted) {
      // debugPrint('[PendingActionsPage] 操作 ${action.actionCode} 已完成，自动标记');
      return true;
    }

    switch (action.actionCode) {
      case 'ADOPTION_WIZARD':
        // 跳转到认种向导
        debugPrint('[PendingActionsPage] ADOPTION_WIZARD: push 到认种向导页面');
        final result = await context.push<bool>(RoutePaths.plantingQuantity);
        debugPrint('[PendingActionsPage] ADOPTION_WIZARD: 认种向导返回，result=$result');
        if (result == true) {
          debugPrint('[PendingActionsPage] ADOPTION_WIZARD: 返回 true，标记完成');
          return true;
        }
        // 认种向导完成后会跳转到合同签署页面，不会返回 true
        // 通过检查是否有待签合同来判断是否完成认种
        debugPrint('[PendingActionsPage] ADOPTION_WIZARD: 返回不是 true，检查是否已完成');
        final alreadyDone = await _checkIfAlreadyCompleted(action);
        debugPrint('[PendingActionsPage] ADOPTION_WIZARD: _checkIfAlreadyCompleted 返回 $alreadyDone');
        return alreadyDone;

      case 'SETTLE_REWARDS':
        // 直接调用结算 API 将可结算收益转入钱包余额
        final rewardService = ref.read(rewardServiceProvider);
        final settleResult = await rewardService.settleToBalance();
        if (settleResult.success) {
          debugPrint('[PendingActionsPage] 结算成功: ${settleResult.settledUsdtAmount} USDT');
          return true;
        }
        // 结算失败，检查是否已经没有可结算收益（可能已经结算过了）
        return await _checkIfAlreadyCompleted(action);

      case 'BIND_PHONE':
        // 跳转到手机号绑定页面
        final result = await context.push<bool>(RoutePaths.kycPhone);
        if (result == true) return true;
        // 页面返回后再次检查是否已完成（用户可能通过其他方式完成了操作）
        return await _checkIfAlreadyCompleted(action);

      case 'FORCE_KYC':
        // 跳转到实名认证页面
        final orderNo = action.actionParams?['orderNo'] as String?;
        final result = await context.push<bool>(RoutePaths.kycEntry, extra: orderNo);
        if (result == true) return true;
        // 页面返回后再次检查是否已完成（用户可能通过其他方式完成了操作）
        return await _checkIfAlreadyCompleted(action);

      case 'SIGN_CONTRACT':
        // 跳转到合同签署页面
        final orderNo = action.actionParams?['orderNo'] as String?;
        if (orderNo != null) {
          final result = await context.push<bool>(
            '${RoutePaths.contractSigning}/$orderNo',
          );
          if (result == true) return true;
          // 页面返回后再次检查是否已完成（用户可能通过其他方式完成了操作）
          return await _checkIfAlreadyCompleted(action);
        }
        // 跳转到待签合同列表
        final result = await context.push<bool>(
          RoutePaths.pendingContracts,
          extra: true, // forceSign = true
        );
        if (result == true) return true;
        // 页面返回后再次检查是否已完成
        return await _checkIfAlreadyCompleted(action);

      case 'UPDATE_PROFILE':
        // 跳转到编辑资料页面
        final result = await context.push<bool>(RoutePaths.editProfile);
        return result == true;

      case 'SPECIAL_DEDUCTION':
        // 特殊扣减操作
        final amount = (action.actionParams?['amount'] ?? 0).toDouble();
        final reason = action.actionParams?['reason'] as String? ?? '管理员扣减';
        final isOfflineSettlement = action.actionParams?['isOfflineSettlement'] == true;

        // 全额线下结算模式：amount 为 0 且 isOfflineSettlement 为 true
        // 普通模式：amount > 0
        if (amount <= 0 && !isOfflineSettlement) {
          debugPrint('[PendingActionsPage] 特殊扣减金额无效且非线下结算模式: $amount');
          return true; // 金额无效且非全额模式，跳过
        }

        final result = await Navigator.of(context).push<bool>(
          MaterialPageRoute(
            builder: (context) => SpecialDeductionPage(
              params: SpecialDeductionParams(
                pendingActionId: action.id.toString(),
                amount: amount,
                reason: reason,
                isOfflineSettlement: isOfflineSettlement,
              ),
            ),
          ),
        );
        return result == true;

      default:
        // 未知操作类型，显示提示并标记为完成
        debugPrint('[PendingActionsPage] 未知操作类型: ${action.actionCode}');
        return true;
    }
  }

  /// 检查操作是否已经完成
  /// 例如：KYC 已经验证过了，手机号已经绑定了，合同已经签署了
  Future<bool> _checkIfAlreadyCompleted(PendingAction action) async {
    try {
      switch (action.actionCode) {
        case 'FORCE_KYC':
          // 检查实名认证(level1)是否已完成
          // FORCE_KYC 待办操作只要求用户完成实名认证，不需要完成所有层级
          final kycService = ref.read(kycServiceProvider);
          final kycStatus = await kycService.getKycStatus();
          if (kycStatus.level1.verified) {
            debugPrint('[PendingActionsPage] 实名认证已完成，跳过 FORCE_KYC 操作');
            return true;
          }
          return false;

        case 'BIND_PHONE':
          // 检查手机号是否已绑定
          final kycService = ref.read(kycServiceProvider);
          final kycStatus = await kycService.getKycStatus();
          if (kycStatus.phoneVerified) {
            // debugPrint('[PendingActionsPage] 手机号已绑定，跳过此操作');
            return true;
          }
          return false;

        case 'SIGN_CONTRACT':
          // 检查是否还有待签署的合同
          final contractService = ref.read(contractSigningServiceProvider);
          final orderNo = action.actionParams?['orderNo'] as String?;
          if (orderNo != null) {
            // 如果指定了订单号，检查该订单的合同是否已签署
            try {
              final task = await contractService.getTask(orderNo);
              if (task.status == ContractSigningStatus.signed) {
                debugPrint('[PendingActionsPage] 合同 $orderNo 已签署，跳过 SIGN_CONTRACT 操作');
                return true;
              }
            } catch (e) {
              // 获取任务失败，可能是订单不存在，继续检查待签列表
              debugPrint('[PendingActionsPage] 获取合同任务失败: $e');
            }
          }
          // 检查是否还有待签署的合同
          final pendingTasks = await contractService.getPendingTasks();
          if (pendingTasks.isEmpty) {
            debugPrint('[PendingActionsPage] 没有待签署的合同，跳过 SIGN_CONTRACT 操作');
            return true;
          }
          return false;

        case 'SETTLE_REWARDS':
          // 检查是否还有可结算的收益
          final rewardService = ref.read(rewardServiceProvider);
          final summary = await rewardService.getMyRewardSummary();
          if (summary.settleableUsdt <= 0) {
            debugPrint('[PendingActionsPage] 没有可结算收益，跳过 SETTLE_REWARDS 操作');
            return true;
          }
          return false;

        case 'ADOPTION_WIZARD':
          // 检查用户是否有已完成支付的认种订单
          // 通过检查订单状态（PAID/FUND_ALLOCATED/MINING_ENABLED）来判断
          final plantingService = ref.read(plantingServiceProvider);
          try {
            final orders = await plantingService.getMyOrders(page: 1, pageSize: 10);
            for (final order in orders) {
              // 检查订单是否已支付、资金已分配或挖矿已启用
              final isCompleted = order.status == PlantingOrderStatus.paid ||
                  order.status == PlantingOrderStatus.fundAllocated ||
                  order.status == PlantingOrderStatus.miningEnabled;
              if (isCompleted) {
                // 检查订单是否在待办操作创建之后创建的
                // 这样可以支持用户多次执行认种向导
                if (order.createdAt.isAfter(action.createdAt)) {
                  debugPrint('[PendingActionsPage] 用户在待办操作后完成了认种订单 ${order.orderNo}，认种向导已完成');
                  return true;
                }
                // 如果订单在待办操作之前但相差不超过24小时，也认为是同一次认种
                // 这是为了兼容待办操作创建有延迟的情况
                final timeDiff = action.createdAt.difference(order.createdAt);
                if (timeDiff.inHours < 24) {
                  debugPrint('[PendingActionsPage] 用户有近期完成的认种订单 ${order.orderNo}（相差${timeDiff.inHours}小时），认种向导已完成');
                  return true;
                }
              }
            }
          } catch (e) {
            debugPrint('[PendingActionsPage] 检查认种订单失败: $e');
          }

          // 备用检查：是否有待签合同（说明认种已完成，只是还没签合同）
          try {
            final contractService = ref.read(contractSigningServiceProvider);
            final pendingTasks = await contractService.getPendingTasks();
            if (pendingTasks.isNotEmpty) {
              debugPrint('[PendingActionsPage] 存在待签合同，认种向导已完成');
              return true;
            }
          } catch (e) {
            debugPrint('[PendingActionsPage] 检查待签合同失败: $e');
          }

          return false;

        // 其他操作类型目前不做预检查
        default:
          return false;
      }
    } catch (e) {
      // debugPrint('[PendingActionsPage] 预检查失败: $e');
      // 检查失败时不跳过，让用户手动完成
      return false;
    }
  }

  /// 所有操作完成，跳转到主页
  void _completeAllActions() {
    if (mounted) {
      debugPrint('[PendingActionsPage] 所有待办操作完成，跳转到主页');
      context.go(RoutePaths.ranking);
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      // 禁止返回
      canPop: false,
      child: Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0xFFFFF7E6),
                Color(0xFFEAE0C8),
              ],
            ),
          ),
          child: SafeArea(
            child: Column(
              children: [
                _buildHeader(),
                Expanded(child: _buildContent()),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          const Icon(
            Icons.assignment_outlined,
            color: Color(0xFFD4AF37),
            size: 48,
          ),
          const SizedBox(height: 12),
          const Text(
            '待办事项',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请完成以下任务后继续使用',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          if (_pendingActions.isNotEmpty) ...[
            const SizedBox(height: 12),
            _buildProgress(),
          ],
        ],
      ),
    );
  }

  Widget _buildProgress() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '进度',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
              Text(
                '$_currentIndex / ${_pendingActions.length}',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFFD4AF37),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          LinearProgressIndicator(
            value: _pendingActions.isEmpty
                ? 0
                : _currentIndex / _pendingActions.length,
            backgroundColor: Colors.grey[300],
            valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
            borderRadius: BorderRadius.circular(4),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Color(0xFFD4AF37)),
            SizedBox(height: 16),
            Text(
              '正在加载待办事项...',
              style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
            ),
          ],
        ),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, color: Colors.red, size: 48),
              const SizedBox(height: 16),
              Text(
                _errorMessage!,
                style: const TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _loadPendingActions,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFD4AF37),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: const Text('重试'),
              ),
            ],
          ),
        ),
      );
    }

    if (_pendingActions.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.check_circle_outline, color: Color(0xFF4CAF50), size: 64),
            SizedBox(height: 16),
            Text(
              '所有待办事项已完成',
              style: TextStyle(
                fontSize: 18,
                color: Color(0xFF4CAF50),
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      );
    }

    if (_currentIndex >= _pendingActions.length) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.check_circle_outline, color: Color(0xFF4CAF50), size: 64),
            SizedBox(height: 16),
            Text(
              '恭喜！所有任务已完成',
              style: TextStyle(
                fontSize: 18,
                color: Color(0xFF4CAF50),
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _pendingActions.length,
      itemBuilder: (context, index) => _buildActionCard(index),
    );
  }

  Widget _buildActionCard(int index) {
    final action = _pendingActions[index];
    final isCompleted = index < _currentIndex;
    final isCurrent = index == _currentIndex;

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
        border: isCurrent
            ? Border.all(color: const Color(0xFFD4AF37), width: 2)
            : isCompleted
                ? Border.all(color: const Color(0xFF4CAF50), width: 1)
                : null,
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            // 状态图标
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: isCompleted
                    ? const Color(0xFF4CAF50)
                    : isCurrent
                        ? const Color(0xFFD4AF37)
                        : Colors.grey[300],
                shape: BoxShape.circle,
              ),
              child: Icon(
                isCompleted
                    ? Icons.check
                    : _getActionIcon(action.actionCode),
                color: Colors.white,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            // 操作信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    action.displayLabel,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: isCompleted
                          ? Colors.grey
                          : const Color(0xFF5D4037),
                      decoration: isCompleted
                          ? TextDecoration.lineThrough
                          : null,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    isCompleted
                        ? '已完成'
                        : isCurrent
                            ? '当前任务'
                            : '待处理',
                    style: TextStyle(
                      fontSize: 12,
                      color: isCompleted
                          ? const Color(0xFF4CAF50)
                          : isCurrent
                              ? const Color(0xFFD4AF37)
                              : Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            // 操作按钮
            if (isCurrent)
              SizedBox(
                width: 72,
                child: ElevatedButton(
                  onPressed: _isExecuting ? null : _executeCurrentAction,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: _isExecuting
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Colors.white,
                          ),
                        )
                      : const Text('开始'),
                ),
              ),
          ],
        ),
      ),
    );
  }

  IconData _getActionIcon(String actionCode) {
    switch (actionCode) {
      case 'ADOPTION_WIZARD':
        return Icons.nature;
      case 'SETTLE_REWARDS':
        return Icons.monetization_on;
      case 'BIND_PHONE':
        return Icons.phone_android;
      case 'FORCE_KYC':
        return Icons.person_outline;
      case 'SIGN_CONTRACT':
        return Icons.description;
      case 'UPDATE_PROFILE':
        return Icons.edit;
      case 'SPECIAL_DEDUCTION':
        return Icons.remove_circle_outline;
      default:
        return Icons.assignment;
    }
  }
}
