import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/wallet_service.dart';

/// 特殊扣减参数
class SpecialDeductionParams {
  final String pendingActionId;
  final double amount;
  final String reason;
  final bool isOfflineSettlement;  // 是否为全额线下结算模式

  SpecialDeductionParams({
    required this.pendingActionId,
    required this.amount,
    required this.reason,
    this.isOfflineSettlement = false,  // 默认为普通模式
  });
}

/// 特殊扣减确认页面
class SpecialDeductionPage extends ConsumerStatefulWidget {
  final SpecialDeductionParams params;

  const SpecialDeductionPage({
    super.key,
    required this.params,
  });

  @override
  ConsumerState<SpecialDeductionPage> createState() =>
      _SpecialDeductionPageState();
}

class _SpecialDeductionPageState extends ConsumerState<SpecialDeductionPage> {
  bool _isLoading = false;
  bool _isExecuting = false;
  String? _errorMessage;
  WalletResponse? _walletInfo;
  UnprocessedSettlementsResult? _unprocessedSettlements;  // 全额模式下的未处理结算记录

  // 判断是否为全额线下结算模式
  bool get _isOfflineSettlementMode => widget.params.isOfflineSettlement || widget.params.amount <= 0;

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

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final walletService = ref.read(walletServiceProvider);
      final accountService = ref.read(accountServiceProvider);

      // 获取钱包信息
      final wallet = await walletService.getMyWallet();

      // 如果是全额模式，还需要查询未处理的结算记录
      UnprocessedSettlementsResult? unprocessed;
      if (_isOfflineSettlementMode) {
        final accountSequence = await accountService.getUserSerialNum();
        if (accountSequence != null && accountSequence.isNotEmpty) {
          unprocessed = await walletService.getUnprocessedSettlements(
            accountSequence: accountSequence,
          );
        }
      }

      setState(() {
        _walletInfo = wallet;
        _unprocessedSettlements = unprocessed;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '加载数据失败: $e';
      });
    }
  }

  Future<void> _executeDeduction() async {
    if (_walletInfo == null) return;

    // 全额模式不需要检查余额（会自动扣减到0）
    if (!_isOfflineSettlementMode) {
      // 普通模式：检查余额是否足够
      if (_walletInfo!.balances.usdt.available < widget.params.amount) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('余额不足，无法执行扣减'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }
    }

    setState(() {
      _isExecuting = true;
      _errorMessage = null;
    });

    try {
      final accountService = ref.read(accountServiceProvider);
      final accountSequence = await accountService.getUserSerialNum();

      if (accountSequence == null || accountSequence.isEmpty) {
        throw Exception('未登录');
      }

      final walletService = ref.read(walletServiceProvider);

      if (_isOfflineSettlementMode) {
        // 全额线下结算模式
        final result = await walletService.executeOfflineSettlementDeduction(
          accountSequence: accountSequence,
          pendingActionId: widget.params.pendingActionId,
          operatorId: 'user:$accountSequence',
          customMemo: widget.params.reason.isNotEmpty ? widget.params.reason : null,
        );

        if (result.success) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(
                  result.deductionCount > 0
                      ? '线下结算完成，共扣减 ${result.deductionCount} 笔，总计 ${result.totalDeducted.toStringAsFixed(2)} 绿积分'
                      : '没有需要扣减的结算记录',
                ),
                backgroundColor: Colors.green,
              ),
            );
            Navigator.of(context).pop(true);
          }
        } else {
          throw Exception('扣减失败');
        }
      } else {
        // 普通特殊扣减模式
        final result = await walletService.executeSpecialDeduction(
          accountSequence: accountSequence,
          pendingActionId: widget.params.pendingActionId,
          amount: widget.params.amount,
          reason: widget.params.reason,
        );

        if (result.success) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('扣减成功，新余额: ${result.newBalance.toStringAsFixed(2)} 绿积分'),
                backgroundColor: Colors.green,
              ),
            );
            Navigator.of(context).pop(true);
          }
        } else {
          throw Exception('扣减失败');
        }
      }
    } catch (e) {
      setState(() {
        _isExecuting = false;
        _errorMessage = '执行扣减失败: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return 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.warning_amber_rounded,
            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],
            ),
          ),
        ],
      ),
    );
  }

  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: _loadData,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFD4AF37),
                  foregroundColor: Colors.white,
                ),
                child: const Text('重试'),
              ),
            ],
          ),
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 扣减信息卡片
          _buildDeductionInfoCard(),
          const SizedBox(height: 16),
          // 钱包余额卡片
          _buildBalanceCard(),
          const SizedBox(height: 24),
          // 确认按钮
          _buildConfirmButton(),
          const SizedBox(height: 16),
          // 提示信息
          _buildNotice(),
        ],
      ),
    );
  }

  Widget _buildDeductionInfoCard() {
    // 全额模式下显示待扣减的结算记录
    if (_isOfflineSettlementMode) {
      return _buildOfflineSettlementCard();
    }

    // 普通模式显示固定金额
    return Container(
      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),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF7E6),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(
                    Icons.remove_circle_outline,
                    color: Color(0xFFD4AF37),
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                const Text(
                  '扣减金额',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Center(
              child: Text(
                '${widget.params.amount.toStringAsFixed(2)} 绿积分',
                style: const TextStyle(
                  fontSize: 32,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFFE53935),
                ),
              ),
            ),
            const SizedBox(height: 20),
            const Divider(),
            const SizedBox(height: 12),
            const Text(
              '扣减原因',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
            const SizedBox(height: 8),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF7E6),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: const Color(0xFFFFD591)),
              ),
              child: Text(
                widget.params.reason,
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF5D4037),
                  height: 1.5,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 全额线下结算模式的卡片
  Widget _buildOfflineSettlementCard() {
    final settlements = _unprocessedSettlements;
    final totalAmount = settlements?.totalAmount ?? 0;
    final count = settlements?.count ?? 0;
    final reason = widget.params.reason.isNotEmpty
        ? widget.params.reason
        : '该收益已由用户与上级间线下完成现金收付';

    return Container(
      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),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: const Color(0xFFE6F4FF),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(
                    Icons.sync_alt,
                    color: Color(0xFF1677FF),
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                const Text(
                  '线下结算扣减',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 说明
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFE6F4FF),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: const Color(0xFF91CAFF)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '此操作将扣减您所有已结算的收益',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF1677FF),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    reason,
                    style: const TextStyle(
                      fontSize: 13,
                      color: Color(0xFF666666),
                      height: 1.5,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),

            // 汇总信息
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF7E6),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: const Color(0xFFFFD591)),
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '待扣减笔数',
                        style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
                      ),
                      Text(
                        '$count 笔',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Color(0xFF5D4037),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '待扣减总额',
                        style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
                      ),
                      Text(
                        '${totalAmount.toStringAsFixed(2)} 绿积分',
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFFE53935),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // 如果有结算记录，显示详情列表
            if (settlements != null && settlements.entries.isNotEmpty) ...[
              const SizedBox(height: 16),
              const Text(
                '结算记录明细',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
              const SizedBox(height: 8),
              Container(
                constraints: const BoxConstraints(maxHeight: 200),
                decoration: BoxDecoration(
                  color: const Color(0xFFFAFAFA),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: const Color(0xFFE0E0E0)),
                ),
                child: ListView.separated(
                  shrinkWrap: true,
                  padding: const EdgeInsets.all(8),
                  itemCount: settlements.entries.length,
                  separatorBuilder: (_, __) => const Divider(height: 1),
                  itemBuilder: (context, index) {
                    final entry = settlements.entries[index];
                    return Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  entry.allocationTypeName,
                                  style: const TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w500,
                                    color: Color(0xFF5D4037),
                                  ),
                                ),
                                const SizedBox(height: 2),
                                Text(
                                  entry.createdAt.toString().substring(0, 10),
                                  style: const TextStyle(
                                    fontSize: 11,
                                    color: Color(0xFF999999),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Text(
                            '${entry.amount.toStringAsFixed(2)} 绿积分',
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Color(0xFFE53935),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ],

            // 如果没有记录
            if (settlements == null || settlements.entries.isEmpty)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                margin: const EdgeInsets.only(top: 16),
                decoration: BoxDecoration(
                  color: const Color(0xFFF5F5F5),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  children: [
                    const Icon(
                      Icons.info_outline,
                      color: Color(0xFF999999),
                      size: 32,
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      '暂无待扣减的结算记录',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: Color(0xFF666666),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _walletInfo != null && (_walletInfo!.balances.usdt.available) > 0
                          ? '当前余额来自充值或转账，非收益结算，无需扣减'
                          : '该用户没有已结算的收益记录',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF999999),
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildBalanceCard() {
    final available = _walletInfo?.balances.usdt.available ?? 0;

    // 全额模式：扣减金额为未处理结算总额（但不超过可用余额）
    final deductionAmount = _isOfflineSettlementMode
        ? (_unprocessedSettlements?.totalAmount ?? 0).clamp(0, available)
        : widget.params.amount;
    final afterDeduction = available - deductionAmount;
    final isInsufficient = !_isOfflineSettlementMode && afterDeduction < 0;

    return Container(
      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),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '当前余额',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF666666),
                  ),
                ),
                Text(
                  '${available.toStringAsFixed(2)} 绿积分',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _isOfflineSettlementMode ? '预计扣减' : '扣减金额',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF666666),
                  ),
                ),
                Text(
                  '-${deductionAmount.toStringAsFixed(2)} 绿积分',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFFE53935),
                  ),
                ),
              ],
            ),
            const Padding(
              padding: EdgeInsets.symmetric(vertical: 12),
              child: Divider(),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '扣减后余额',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
                Text(
                  '${afterDeduction.toStringAsFixed(2)} 绿积分',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: isInsufficient ? Colors.red : const Color(0xFF4CAF50),
                  ),
                ),
              ],
            ),
            if (isInsufficient) ...[
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: const Color(0xFFFFEBEE),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Row(
                  children: [
                    Icon(Icons.error_outline, color: Colors.red, size: 20),
                    SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '余额不足，无法执行此扣减操作',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.red,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildConfirmButton() {
    final available = _walletInfo?.balances.usdt.available ?? 0;
    final isInsufficient = available < widget.params.amount;

    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: _isExecuting || isInsufficient ? null : _executeDeduction,
        style: ElevatedButton.styleFrom(
          backgroundColor: isInsufficient ? Colors.grey : const Color(0xFFE53935),
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(vertical: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          disabledBackgroundColor: Colors.grey[300],
        ),
        child: _isExecuting
            ? const SizedBox(
                width: 24,
                height: 24,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  color: Colors.white,
                ),
              )
            : Text(
                isInsufficient ? '余额不足' : '确认扣减',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
      ),
    );
  }

  Widget _buildNotice() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF7E6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFFFFD591)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.info_outline,
                color: Color(0xFFD46B08),
                size: 20,
              ),
              SizedBox(width: 8),
              Text(
                '温馨提示',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFFD46B08),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            '• 此操作由系统管理员发起\n'
            '• 扣减将从您的绿积分余额中直接扣除\n'
            '• 扣减完成后无法撤销\n'
            '• 如有疑问，请联系客服',
            style: TextStyle(
              fontSize: 13,
              color: Colors.grey[700],
              height: 1.6,
            ),
          ),
        ],
      ),
    );
  }
}
