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/transfer_service.dart';

// ============================================
// [2026-02-19] 树转让详情页（纯新增）
// ============================================
//
// 展示单笔转让订单的详细信息：
// - 状态 badge + 基本信息
// - Saga 进度时间线
// - 操作按钮（卖方确认 / 取消）
//
// === 回滚方式 ===
// 删除 features/transfer/ 目录

/// 转让详情页
class TransferDetailPage extends ConsumerStatefulWidget {
  final String transferOrderNo;

  const TransferDetailPage({super.key, required this.transferOrderNo});

  @override
  ConsumerState<TransferDetailPage> createState() => _TransferDetailPageState();
}

class _TransferDetailPageState extends ConsumerState<TransferDetailPage> {
  TransferOrderDetail? _order;
  bool _isLoading = true;
  String? _errorMessage;
  bool _isActionLoading = false;

  // Saga 步骤定义
  static const _sagaSteps = [
    {'status': 'PENDING', 'label': '待卖方确认'},
    {'status': 'SELLER_CONFIRMED', 'label': '卖方已确认'},
    {'status': 'PAYMENT_FROZEN', 'label': '买方资金冻结'},
    {'status': 'TREES_LOCKED', 'label': '卖方树锁定'},
    {'status': 'OWNERSHIP_TRANSFERRED', 'label': '所有权变更'},
    {'status': 'CONTRIBUTION_ADJUSTED', 'label': '算力调整'},
    {'status': 'STATS_UPDATED', 'label': '团队统计更新'},
    {'status': 'PAYMENT_SETTLED', 'label': '资金结算'},
    {'status': 'COMPLETED', 'label': '转让完成'},
  ];

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

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

    try {
      final service = ref.read(transferServiceProvider);
      final order = await service.getTransferDetail(widget.transferOrderNo);
      if (mounted) {
        setState(() {
          _order = order;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString();
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _handleSellerConfirm() async {
    setState(() => _isActionLoading = true);
    try {
      final service = ref.read(transferServiceProvider);
      await service.sellerConfirm(widget.transferOrderNo);
      if (mounted) _loadData();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('确认失败: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isActionLoading = false);
    }
  }

  Future<void> _handleCancel() async {
    final reason = await showDialog<String>(
      context: context,
      builder: (ctx) {
        String text = '';
        return AlertDialog(
          backgroundColor: const Color(0xFFFFF7E6),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: const Text(
            '取消转让',
            style: TextStyle(color: Color(0xFF5D4037), fontWeight: FontWeight.w700),
          ),
          content: TextField(
            onChanged: (v) => text = v,
            style: const TextStyle(color: Color(0xFF5D4037)),
            decoration: InputDecoration(
              hintText: '取消原因（可选）',
              hintStyle: const TextStyle(color: Color(0xFF745D43)),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color(0xFFEAE0C8)),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: const BorderSide(color: Color(0xFFD4AF37)),
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(ctx),
              child: const Text('返回', style: TextStyle(color: Color(0xFF745D43))),
            ),
            TextButton(
              onPressed: () => Navigator.pop(ctx, text.isEmpty ? '用户主动取消' : text),
              child: const Text('确认取消', style: TextStyle(color: Color(0xFFE65100))),
            ),
          ],
        );
      },
    );

    if (reason == null) return;

    setState(() => _isActionLoading = true);
    try {
      final service = ref.read(transferServiceProvider);
      await service.cancelTransfer(widget.transferOrderNo, reason: reason);
      if (mounted) _loadData();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('取消失败: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isActionLoading = false);
    }
  }

  @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: _buildBody()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => context.pop(),
            child: Container(
              width: 32,
              height: 32,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back_ios,
                color: Color(0xFFD4AF37),
                size: 20,
              ),
            ),
          ),
          const SizedBox(width: 4),
          GestureDetector(
            onTap: () => context.pop(),
            child: const Text(
              '返回',
              style: TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.5,
                color: Color(0xFFD4AF37),
              ),
            ),
          ),
          const SizedBox(width: 42),
          const Expanded(
            child: Text(
              '转让详情',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator(color: Color(0xFFD4AF37)));
    }
    if (_errorMessage != null || _order == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Color(0xFFE65100), size: 32),
            const SizedBox(height: 8),
            const Text('加载失败', style: TextStyle(color: Color(0xFF5D4037), fontSize: 16)),
            const SizedBox(height: 8),
            GestureDetector(
              onTap: _loadData,
              child: const Text(
                '点击重试',
                style: TextStyle(
                  color: Color(0xFFD4AF37),
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      );
    }

    final order = _order!;
    return RefreshIndicator(
      onRefresh: _loadData,
      color: const Color(0xFFD4AF37),
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoCard(order),
            const SizedBox(height: 16),
            _buildSagaTimeline(order),
            const SizedBox(height: 16),
            if (order.statusLogs.isNotEmpty) _buildStatusLogs(order),
            const SizedBox(height: 16),
            _buildActionButtons(order),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoCard(TransferOrderDetail order) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 6,
            offset: Offset(0, 4),
          ),
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 单号 + 状态
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  order.transferOrderNo,
                  style: const TextStyle(fontSize: 14, color: Color(0xFF745D43), fontFamily: 'Inter'),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              _buildStatusBadge(order.status),
            ],
          ),
          const SizedBox(height: 16),
          _infoRow('卖方', order.sellerAccountSequence),
          _infoRow('买方', order.buyerAccountSequence),
          _infoRow('棵数', '${order.treeCount} 棵'),
          _infoRow('单价', '${order.pricePerTree.toStringAsFixed(0)} USDT'),
          _infoRow('总价', '${order.totalPrice.toStringAsFixed(0)} USDT'),
          _infoRow('手续费', '${order.platformFeeAmount.toStringAsFixed(2)} USDT (${(order.platformFeeRate * 100).toStringAsFixed(1)}%)'),
          _infoRow('卖方到账', '${order.sellerReceiveAmount.toStringAsFixed(2)} USDT'),
          _infoRow('创建时间', _formatDateTime(order.createdAt)),
          if (order.completedAt != null)
            _infoRow('完成时间', _formatDateTime(order.completedAt!)),
          if (order.cancelReason != null)
            _infoRow('取消原因', order.cancelReason!),
        ],
      ),
    );
  }

  Widget _infoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 13, color: Color(0xFF745D43))),
          Text(value, style: const TextStyle(fontSize: 13, color: Color(0xFF5D4037), fontFamily: 'Inter')),
        ],
      ),
    );
  }

  Widget _buildSagaTimeline(TransferOrderDetail order) {
    final statusApiMap = {
      'pending': 'PENDING',
      'sellerConfirmed': 'SELLER_CONFIRMED',
      'paymentFrozen': 'PAYMENT_FROZEN',
      'treesLocked': 'TREES_LOCKED',
      'ownershipTransferred': 'OWNERSHIP_TRANSFERRED',
      'contributionAdjusted': 'CONTRIBUTION_ADJUSTED',
      'statsUpdated': 'STATS_UPDATED',
      'paymentSettled': 'PAYMENT_SETTLED',
      'completed': 'COMPLETED',
    };
    final apiStatus = statusApiMap[order.status.name] ?? order.status.name.toUpperCase();
    final currentIdx = _sagaSteps.indexWhere((s) => s['status'] == apiStatus);
    final isFailed = order.status == TransferOrderStatus.failed ||
        order.status == TransferOrderStatus.rollingBack ||
        order.status == TransferOrderStatus.rolledBack;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 6,
            offset: Offset(0, 4),
          ),
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Saga 进度',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF5D4037)),
          ),
          const SizedBox(height: 16),
          ...List.generate(_sagaSteps.length, (idx) {
            final step = _sagaSteps[idx];
            final isCompleted = !isFailed && (idx < currentIdx || (order.isTerminal && idx <= currentIdx));
            final isCurrent = idx == currentIdx && !order.isTerminal && !isFailed;
            final isFailedStep = isFailed && idx == currentIdx;

            Color dotColor = const Color(0xFFEAE0C8);
            Color dotBorder = const Color(0xFFEAE0C8);
            if (isCompleted) {
              dotColor = const Color(0xFF52C41A);
              dotBorder = const Color(0xFF52C41A);
            } else if (isCurrent) {
              dotColor = const Color(0xFFD4AF37).withValues(alpha: 0.3);
              dotBorder = const Color(0xFFD4AF37);
            } else if (isFailedStep) {
              dotColor = const Color(0xFFFF4D4F);
              dotBorder = const Color(0xFFFF4D4F);
            }

            // Find log entry for this step
            final logEntry = order.statusLogs
                .where((l) => l.toStatus == step['status'])
                .toList();
            final logTime = logEntry.isNotEmpty ? logEntry.first.createdAt : null;

            return Padding(
              padding: EdgeInsets.only(bottom: idx < _sagaSteps.length - 1 ? 16 : 0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Column(
                    children: [
                      Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: dotColor,
                          shape: BoxShape.circle,
                          border: Border.all(color: dotBorder, width: 2),
                        ),
                        child: isCompleted
                            ? const Icon(Icons.check, size: 12, color: Colors.white)
                            : isFailedStep
                                ? const Icon(Icons.close, size: 12, color: Colors.white)
                                : null,
                      ),
                      if (idx < _sagaSteps.length - 1)
                        Container(
                          width: 2,
                          height: 20,
                          color: isCompleted
                              ? const Color(0xFF52C41A).withValues(alpha: 0.4)
                              : const Color(0xFFEAE0C8),
                        ),
                    ],
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          step['label']!,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: (isCurrent || isCompleted) ? FontWeight.w600 : FontWeight.w400,
                            color: (isCurrent || isCompleted)
                                ? const Color(0xFF5D4037)
                                : const Color(0xFF745D43),
                          ),
                        ),
                        if (logTime != null)
                          Text(
                            _formatDateTime(logTime),
                            style: const TextStyle(fontSize: 11, color: Color(0xFF745D43)),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _buildStatusLogs(TransferOrderDetail order) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 6,
            offset: Offset(0, 4),
          ),
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '状态变更日志',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF5D4037)),
          ),
          const SizedBox(height: 12),
          ...order.statusLogs.map((log) => Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: Row(
                  children: [
                    Expanded(
                      flex: 2,
                      child: Text(
                        '${log.fromStatus} → ${log.toStatus}',
                        style: const TextStyle(fontSize: 12, color: Color(0xFF745D43), fontFamily: 'Inter'),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        _formatDateTime(log.createdAt),
                        style: const TextStyle(fontSize: 11, color: Color(0xFF745D43)),
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }

  Widget _buildActionButtons(TransferOrderDetail order) {
    if (order.isTerminal) return const SizedBox.shrink();

    return Row(
      children: [
        // 卖方确认按钮
        if (order.isPendingSellerConfirm)
          Expanded(
            child: GestureDetector(
              onTap: _isActionLoading ? null : _handleSellerConfirm,
              child: Container(
                height: 56,
                decoration: BoxDecoration(
                  color: _isActionLoading
                      ? const Color(0xFFD4AF37).withValues(alpha: 0.5)
                      : const Color(0xFFD4AF37),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: !_isActionLoading
                      ? const [
                          BoxShadow(
                            color: Color(0x1A000000),
                            blurRadius: 15,
                            offset: Offset(0, 10),
                          ),
                        ]
                      : null,
                ),
                child: Center(
                  child: Text(
                    _isActionLoading ? '处理中...' : '确认转让',
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ),
        if (order.isPendingSellerConfirm) const SizedBox(width: 12),
        // 取消按钮
        if (order.isCancellable)
          Expanded(
            child: GestureDetector(
              onTap: _isActionLoading ? null : _handleCancel,
              child: Container(
                height: 56,
                decoration: BoxDecoration(
                  color: const Color(0x99FFFFFF),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: const Color(0xFFE65100)),
                ),
                child: Center(
                  child: const Text(
                    '取消转让',
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      color: Color(0xFFE65100),
                    ),
                  ),
                ),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildStatusBadge(TransferOrderStatus status) {
    final info = _getStatusInfo(status);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: info.color.withValues(alpha: 0.15),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Text(
        info.label,
        style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: info.color),
      ),
    );
  }

  _StatusInfo _getStatusInfo(TransferOrderStatus status) {
    switch (status) {
      case TransferOrderStatus.pending:
        return _StatusInfo('待确认', const Color(0xFFD48806));
      case TransferOrderStatus.sellerConfirmed:
        return _StatusInfo('卖方已确认', const Color(0xFF096DD9));
      case TransferOrderStatus.paymentFrozen:
      case TransferOrderStatus.treesLocked:
      case TransferOrderStatus.ownershipTransferred:
      case TransferOrderStatus.contributionAdjusted:
      case TransferOrderStatus.statsUpdated:
      case TransferOrderStatus.paymentSettled:
        return _StatusInfo('处理中', const Color(0xFF2F54EB));
      case TransferOrderStatus.completed:
        return _StatusInfo('已完成', const Color(0xFF52C41A));
      case TransferOrderStatus.cancelled:
        return _StatusInfo('已取消', const Color(0xFF8C8C8C));
      case TransferOrderStatus.failed:
        return _StatusInfo('失败', const Color(0xFFCF1322));
      case TransferOrderStatus.rollingBack:
        return _StatusInfo('补偿中', const Color(0xFFD4380D));
      case TransferOrderStatus.rolledBack:
        return _StatusInfo('已回滚', const Color(0xFF595959));
    }
  }

  String _formatDateTime(DateTime dt) {
    final local = dt.toLocal();
    return '${local.year}-${local.month.toString().padLeft(2, '0')}-${local.day.toString().padLeft(2, '0')} '
        '${local.hour.toString().padLeft(2, '0')}:${local.minute.toString().padLeft(2, '0')}';
  }
}

class _StatusInfo {
  final String label;
  final Color color;
  _StatusInfo(this.label, this.color);
}
