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';
import '../../../../routes/route_paths.dart';

// ============================================
// [2026-02-19] 树转让记录列表页（纯新增）
// ============================================
//
// 展示用户的树转让记录，包括作为卖方和买方的所有转让订单。
//
// === 页面结构 ===
// ┌─ AppBar（转让记录）
// ├─ Tab: 全部 / 转出 / 转入
// └─ ListView（转让订单卡片列表）
//
// === 回滚方式 ===
// 删除 features/transfer/ 目录

/// 转让记录列表页
class TransferListPage extends ConsumerStatefulWidget {
  const TransferListPage({super.key});

  @override
  ConsumerState<TransferListPage> createState() => _TransferListPageState();
}

class _TransferListPageState extends ConsumerState<TransferListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<TransferOrder> _orders = [];
  bool _isLoading = true;
  String? _errorMessage;

  // Tab 角色过滤: null=全部, 'seller'=转出, 'buyer'=转入
  final List<String?> _tabRoles = [null, 'seller', 'buyer'];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      if (!_tabController.indexIsChanging) {
        _loadData();
      }
    });
    _loadData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

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

    try {
      final service = ref.read(transferServiceProvider);
      final role = _tabRoles[_tabController.index];
      final orders = await service.getMyTransfers(role: role);
      if (mounted) {
        setState(() {
          _orders = orders;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString();
          _isLoading = 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(),
              _buildTabBar(),
              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 _buildTabBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(12),
      ),
      child: TabBar(
        controller: _tabController,
        indicatorColor: const Color(0xFFD4AF37),
        indicatorSize: TabBarIndicatorSize.label,
        labelColor: const Color(0xFFD4AF37),
        unselectedLabelColor: const Color(0xFF745D43),
        labelStyle: const TextStyle(
          fontSize: 14,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w600,
        ),
        unselectedLabelStyle: const TextStyle(
          fontSize: 14,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w400,
        ),
        dividerColor: Colors.transparent,
        tabs: const [
          Tab(text: '全部'),
          Tab(text: '转出'),
          Tab(text: '转入'),
        ],
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: Color(0xFFD4AF37)),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Color(0xFFE65100), size: 32),
            const SizedBox(height: 8),
            Text(
              '加载失败',
              style: const TextStyle(color: Color(0xFF5D4037), fontSize: 16),
            ),
            const SizedBox(height: 4),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: Text(
                _errorMessage ?? '',
                style: const TextStyle(color: Color(0xFF999999), fontSize: 11),
                textAlign: TextAlign.center,
                maxLines: 5,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const SizedBox(height: 8),
            GestureDetector(
              onTap: _loadData,
              child: const Text(
                '点击重试',
                style: TextStyle(
                  color: Color(0xFFD4AF37),
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      );
    }

    if (_orders.isEmpty) {
      return Center(
        child: Text(
          '暂无转让记录',
          style: const TextStyle(color: Color(0xFF745D43), fontSize: 16),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      color: const Color(0xFFD4AF37),
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _orders.length,
        itemBuilder: (context, index) => _buildOrderCard(_orders[index]),
      ),
    );
  }

  Widget _buildOrderCard(TransferOrder order) {
    final statusInfo = _getStatusInfo(order.status);

    return GestureDetector(
      onTap: () {
        context.push('${RoutePaths.transferDetail}/${order.transferOrderNo}');
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        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: 13,
                      fontFamily: 'Inter',
                      color: Color(0xFF745D43),
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: statusInfo.color.withValues(alpha: 0.15),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Text(
                    statusInfo.label,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w500,
                      color: statusInfo.color,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // 卖方 → 买方
            Row(
              children: [
                Text(
                  order.sellerAccountSequence,
                  style: const TextStyle(fontSize: 14, color: Color(0xFF5D4037), fontFamily: 'Inter'),
                ),
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  child: Icon(Icons.arrow_forward, size: 16, color: Color(0xFFD4AF37)),
                ),
                Text(
                  order.buyerAccountSequence,
                  style: const TextStyle(fontSize: 14, color: Color(0xFF5D4037), fontFamily: 'Inter'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            // 棵数 + 价格
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${order.treeCount} 棵',
                  style: const TextStyle(fontSize: 14, color: Color(0xFF745D43)),
                ),
                Text(
                  '${order.totalPrice.toStringAsFixed(0)} USDT',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFFD4AF37),
                    fontFamily: 'Inter',
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            // 时间
            Text(
              _formatDateTime(order.createdAt),
              style: const TextStyle(fontSize: 12, color: Color(0xFF745D43)),
            ),
          ],
        ),
      ),
    );
  }

  _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);
}
