import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/wallet_service.dart';
import '../../../../core/services/reward_service.dart';
import '../../../../core/services/pre_planting_service.dart';
import '../../../../core/utils/date_utils.dart';

/// 账本明细页面 - 显示用户的流水账、统计图表和筛选功能
class LedgerDetailPage extends ConsumerStatefulWidget {
  const LedgerDetailPage({super.key});

  @override
  ConsumerState<LedgerDetailPage> createState() => _LedgerDetailPageState();
}

class _LedgerDetailPageState extends ConsumerState<LedgerDetailPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late ScrollController _filterScrollController;

  // 数据状态
  bool _isLoading = true;
  LedgerStatistics? _statistics;
  LedgerTrend? _trend;
  PaginatedLedger? _ledger;
  String? _errorMessage;

  // 筛选条件
  String? _selectedEntryType;
  int _selectedFilterIndex = 0;
  int _currentPage = 1;
  static const int _pageSize = 20;

  // [2026-03-01] 用户是否已无待领取奖励（用于标注 REWARD_PENDING 流水）
  bool _userHasNoPending = false;

  // 流水类型选项
  final List<Map<String, String>> _entryTypes = [
    {'value': '', 'label': '全部'},
    {'value': 'TRANSFER_IN', 'label': '转入'},
    {'value': 'TRANSFER_OUT', 'label': '转出'},
    {'value': 'PLANT_PAYMENT', 'label': '认种支付'},
    {'value': 'REWARD_TO_SETTLEABLE', 'label': '分享收益'},
    {'value': 'SYSTEM_ALLOCATION', 'label': '权益收入'},
    {'value': 'REWARD_EXPIRED', 'label': '奖励过期'},
    {'value': 'WITHDRAWAL', 'label': '提现'},
    {'value': 'REWARD_SETTLED', 'label': '结算'},
    {'value': 'DEPOSIT_KAVA', 'label': '充值'},
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _filterScrollController = ScrollController();
    _loadData();
  }

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

  /// 加载所有数据
  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

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

      // 并行加载统计、趋势和钱包信息
      final results = await Future.wait([
        walletService.getLedgerStatistics(),
        walletService.getLedgerTrend(days: 30),
        walletService.getLedger(
          page: _currentPage,
          pageSize: _pageSize,
          entryType: _selectedEntryType,
        ),
        walletService.getMyWallet(),  // [2026-03-01] 获取 pendingUsdt 判断是否还有待领取
      ]);

      if (mounted) {
        final ledgerData = results[2] as PaginatedLedger;
        final walletInfo = results[3] as WalletResponse;

        // 调试：打印加载的流水数据
        debugPrint('[LedgerDetailPage] ======== 加载流水数据 ========');
        debugPrint('[LedgerDetailPage] 共 ${ledgerData.data.length} 条, 总计 ${ledgerData.total} 条');
        for (int i = 0; i < ledgerData.data.length && i < 10; i++) {
          final entry = ledgerData.data[i];
          debugPrint('[LedgerDetailPage] [$i] entryType=${entry.entryType}, allocationType=${entry.allocationType}, displayName=${entry.displayName}, memo=${entry.memo}');
        }
        debugPrint('[LedgerDetailPage] ================================');

        setState(() {
          _statistics = results[0] as LedgerStatistics;
          _trend = results[1] as LedgerTrend;
          _ledger = ledgerData;
          _userHasNoPending = walletInfo.rewards.pendingUsdt <= 0;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('[LedgerDetailPage] 加载数据失败: $e');
      if (mounted) {
        setState(() {
          _errorMessage = '加载失败: $e';
          _isLoading = false;
        });
      }
    }
  }

  /// 加载更多流水
  Future<void> _loadMoreLedger() async {
    if (_ledger == null || _currentPage >= _ledger!.totalPages) return;

    try {
      final walletService = ref.read(walletServiceProvider);
      final nextPage = _currentPage + 1;
      final newLedger = await walletService.getLedger(
        page: nextPage,
        pageSize: _pageSize,
        entryType: _selectedEntryType,
      );

      if (mounted) {
        setState(() {
          _currentPage = nextPage;
          _ledger = PaginatedLedger(
            data: [..._ledger!.data, ...newLedger.data],
            total: newLedger.total,
            page: nextPage,
            pageSize: _pageSize,
            totalPages: newLedger.totalPages,
          );
        });
      }
    } catch (e) {
      debugPrint('[LedgerDetailPage] 加载更多失败: $e');
    }
  }

  /// 筛选流水类型
  Future<void> _filterByEntryType(String? entryType, int index) async {
    // 保存当前滚动位置
    final scrollOffset = _filterScrollController.hasClients
        ? _filterScrollController.offset
        : 0.0;

    setState(() {
      _selectedEntryType = entryType?.isEmpty == true ? null : entryType;
      _selectedFilterIndex = index;
      _currentPage = 1;
      _isLoading = true;
    });

    // 恢复滚动位置
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_filterScrollController.hasClients) {
        _filterScrollController.jumpTo(scrollOffset);
      }
    });

    try {
      final walletService = ref.read(walletServiceProvider);
      final newLedger = await walletService.getLedger(
        page: 1,
        pageSize: _pageSize,
        entryType: _selectedEntryType,
      );

      if (mounted) {
        setState(() {
          _ledger = newLedger;
          _isLoading = false;
        });

        // 数据加载完成后再次确保滚动位置正确
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (_filterScrollController.hasClients) {
            _filterScrollController.jumpTo(scrollOffset);
          }
        });
      }
    } catch (e) {
      debugPrint('[LedgerDetailPage] 筛选失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 格式化金额
  String _formatAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  /// 格式化日期 (UTC -> 本地时间)
  String _formatDate(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }

  /// 格式化短日期 (UTC -> 本地时间)
  String _formatShortDate(String date) {
    return DateTimeUtils.formatShortDateFromString(date);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              _buildAppBar(),
              // Tab 切换
              _buildTabBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : _errorMessage != null
                        ? _buildErrorView()
                        : TabBarView(
                            controller: _tabController,
                            children: [
                              _buildStatisticsTab(),
                              _buildLedgerListTab(),
                            ],
                          ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildAppBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: const Icon(
              Icons.arrow_back_ios,
              color: Color(0xFF5D4037),
              size: 20,
            ),
          ),
          const SizedBox(width: 8),
          const Text(
            '账本明细',
            style: TextStyle(
              fontSize: 18,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w700,
              color: Color(0xFF5D4037),
            ),
          ),
          const Spacer(),
          // 刷新按钮
          GestureDetector(
            onTap: _loadData,
            child: const Icon(
              Icons.refresh,
              color: Color(0xFF5D4037),
              size: 24,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建 Tab 切换栏
  Widget _buildTabBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: const Color(0x1A8B5A2B),
        borderRadius: BorderRadius.circular(8),
      ),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          color: const Color(0xFFD4AF37),
          borderRadius: BorderRadius.circular(8),
        ),
        indicatorSize: TabBarIndicatorSize.tab,
        labelColor: Colors.white,
        unselectedLabelColor: const Color(0xFF5D4037),
        labelStyle: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
        ),
        tabs: const [
          Tab(text: '统计概览'),
          Tab(text: '流水明细'),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 48,
            color: Color(0xFF8B5A2B),
          ),
          const SizedBox(height: 16),
          Text(
            _errorMessage ?? '加载失败',
            style: const TextStyle(
              color: Color(0xFF5D4037),
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadData,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFD4AF37),
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 构建统计概览 Tab
  Widget _buildStatisticsTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 收支概览卡片
          _buildSummaryCard(),
          const SizedBox(height: 16),
          // 趋势图表
          _buildTrendChart(),
          const SizedBox(height: 16),
          // 按类型统计
          _buildTypeBreakdown(),
        ],
      ),
    );
  }

  /// 构建收支概览卡片
  Widget _buildSummaryCard() {
    final stats = _statistics;
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          const Text(
            '收支概览',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: _buildSummaryItem(
                  '总收入',
                  stats?.totalIncome ?? 0,
                  const Color(0xFF4CAF50),
                  Icons.arrow_downward,
                ),
              ),
              Container(
                width: 1,
                height: 60,
                color: const Color(0x1A8B5A2B),
              ),
              Expanded(
                child: _buildSummaryItem(
                  '总支出',
                  stats?.totalExpense ?? 0,
                  const Color(0xFFE53935),
                  Icons.arrow_upward,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: const Color(0x1AD4AF37),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '净收益',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF5D4037),
                  ),
                ),
                Flexible(
                  child: FittedBox(
                    fit: BoxFit.scaleDown,
                    alignment: Alignment.centerRight,
                    child: Text(
                      '${(stats?.netAmount ?? 0) >= 0 ? '+' : ''}${_formatAmount(stats?.netAmount ?? 0)} 绿积分',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                        color: (stats?.netAmount ?? 0) >= 0
                            ? const Color(0xFF4CAF50)
                            : const Color(0xFFE53935),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
          Text(
            '共 ${stats?.totalCount ?? 0} 笔交易',
            style: const TextStyle(
              fontSize: 12,
              color: Color(0x995D4037),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建收支概览项
  Widget _buildSummaryItem(String label, double amount, Color color, IconData icon) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 16, color: color),
            const SizedBox(width: 4),
            Text(
              label,
              style: const TextStyle(
                fontSize: 12,
                color: Color(0x995D4037),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        FittedBox(
          fit: BoxFit.scaleDown,
          child: Text(
            _formatAmount(amount),
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
              color: color,
            ),
          ),
        ),
        const Text(
          '绿积分',
          style: TextStyle(
            fontSize: 10,
            color: Color(0x995D4037),
          ),
        ),
      ],
    );
  }

  /// 构建趋势图表
  Widget _buildTrendChart() {
    final trend = _trend;
    if (trend == null || trend.dailyTrend.isEmpty) {
      return const SizedBox.shrink();
    }

    // 找出最大值用于计算比例
    double maxValue = 1;
    for (final item in trend.dailyTrend) {
      if (item.income > maxValue) maxValue = item.income;
      if (item.expense > maxValue) maxValue = item.expense;
    }

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '近30天趋势',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: Color(0xFF5D4037),
                ),
              ),
              Row(
                children: [
                  _buildLegendItem('收入', const Color(0xFF4CAF50)),
                  const SizedBox(width: 12),
                  _buildLegendItem('支出', const Color(0xFFE53935)),
                ],
              ),
            ],
          ),
          const SizedBox(height: 20),
          // 简化的柱状图
          SizedBox(
            height: 120,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // 只显示最近7天
                ...trend.dailyTrend.reversed.take(7).toList().reversed.map((item) {
                  final incomeHeight = (item.income / maxValue) * 100;
                  final expenseHeight = (item.expense / maxValue) * 100;
                  return Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 2),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Container(
                                width: 8,
                                height: incomeHeight.clamp(2, 100),
                                decoration: BoxDecoration(
                                  color: const Color(0xFF4CAF50),
                                  borderRadius: BorderRadius.circular(2),
                                ),
                              ),
                              const SizedBox(width: 2),
                              Container(
                                width: 8,
                                height: expenseHeight.clamp(2, 100),
                                decoration: BoxDecoration(
                                  color: const Color(0xFFE53935),
                                  borderRadius: BorderRadius.circular(2),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 4),
                          Text(
                            _formatShortDate(item.date),
                            style: const TextStyle(
                              fontSize: 8,
                              color: Color(0x995D4037),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }),
              ],
            ),
          ),
          const SizedBox(height: 16),
          // 期间汇总
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildPeriodSummary('期间收入', trend.periodIncome, const Color(0xFF4CAF50)),
              _buildPeriodSummary('期间支出', trend.periodExpense, const Color(0xFFE53935)),
              _buildPeriodSummary('期间净收益', trend.periodNet,
                  trend.periodNet >= 0 ? const Color(0xFF4CAF50) : const Color(0xFFE53935)),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建图例项
  Widget _buildLegendItem(String label, Color color) {
    return Row(
      children: [
        Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 10,
            color: Color(0x995D4037),
          ),
        ),
      ],
    );
  }

  /// 构建期间汇总项
  Widget _buildPeriodSummary(String label, double amount, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 10,
            color: Color(0x995D4037),
          ),
        ),
        const SizedBox(height: 4),
        FittedBox(
          fit: BoxFit.scaleDown,
          child: Text(
            _formatAmount(amount),
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: color,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建按类型统计
  Widget _buildTypeBreakdown() {
    final stats = _statistics;
    if (stats == null || stats.byEntryType.isEmpty) {
      return const SizedBox.shrink();
    }

    // 按金额绝对值排序
    final sortedTypes = List<EntryTypeSummary>.from(stats.byEntryType)
      ..sort((a, b) => b.totalAmount.abs().compareTo(a.totalAmount.abs()));

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '按类型统计',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 16),
          ...sortedTypes.take(8).map((item) => _buildTypeItem(item)),
        ],
      ),
    );
  }

  /// 构建类型统计项
  Widget _buildTypeItem(EntryTypeSummary item) {
    final isIncome = item.totalAmount > 0;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: isIncome
                  ? const Color(0x1A4CAF50)
                  : const Color(0x1AE53935),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              isIncome ? Icons.arrow_downward : Icons.arrow_upward,
              size: 16,
              color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.entryTypeName,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF5D4037),
                  ),
                ),
                Text(
                  '${item.count} 笔',
                  style: const TextStyle(
                    fontSize: 10,
                    color: Color(0x995D4037),
                  ),
                ),
              ],
            ),
          ),
          Flexible(
            child: FittedBox(
              fit: BoxFit.scaleDown,
              alignment: Alignment.centerRight,
              child: Text(
                '${isIncome ? '+' : ''}${_formatAmount(item.totalAmount)}',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建流水明细 Tab
  Widget _buildLedgerListTab() {
    return Column(
      children: [
        // 筛选栏
        _buildFilterBar(),
        // 流水列表
        Expanded(
          child: _ledger == null || _ledger!.data.isEmpty
              ? _buildEmptyView()
              : _buildLedgerList(),
        ),
      ],
    );
  }

  /// 构建筛选栏
  Widget _buildFilterBar() {
    return Container(
      height: 44,
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: ListView.builder(
        controller: _filterScrollController,
        scrollDirection: Axis.horizontal,
        itemCount: _entryTypes.length,
        itemBuilder: (context, index) {
          final type = _entryTypes[index];
          final isSelected = _selectedFilterIndex == index;
          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              onTap: () => _filterByEntryType(type['value'], index),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: isSelected ? const Color(0xFFD4AF37) : const Color(0x1A8B5A2B),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Center(
                  child: Text(
                    type['label']!,
                    style: TextStyle(
                      fontSize: 12,
                      color: isSelected ? Colors.white : const Color(0xFF5D4037),
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建空视图
  Widget _buildEmptyView() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.receipt_long_outlined,
            size: 64,
            color: Color(0x808B5A2B),
          ),
          SizedBox(height: 16),
          Text(
            '暂无流水记录',
            style: TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建流水列表
  Widget _buildLedgerList() {
    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is ScrollEndNotification &&
            notification.metrics.extentAfter < 100) {
          _loadMoreLedger();
        }
        return false;
      },
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: _ledger!.data.length + 1,
        itemBuilder: (context, index) {
          if (index == _ledger!.data.length) {
            // 底部加载更多指示器
            if (_currentPage < _ledger!.totalPages) {
              return const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                    ),
                  ),
                ),
              );
            }
            return Padding(
              padding: const EdgeInsets.all(16),
              child: Center(
                child: Text(
                  '共 ${_ledger!.total} 条记录',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0x995D4037),
                  ),
                ),
              ),
            );
          }

          final entry = _ledger!.data[index];
          return _buildLedgerItem(entry);
        },
      ),
    );
  }

  /// 构建流水项
  Widget _buildLedgerItem(LedgerEntry entry) {
    final isIncome = entry.isIncome;
    // 可点击查看详情的类型：认种支付、权益分配、结算、提现、转入、转出
    final bool isPlantPayment = entry.entryType == 'PLANT_PAYMENT' && entry.refOrderId != null;
    final bool isRewardEntry = entry.allocationType != null;
    final bool isSettlementEntry = entry.entryType == 'REWARD_SETTLED';
    final bool isWithdrawalEntry = entry.entryType == 'WITHDRAWAL';
    final bool isTransferEntry = entry.entryType == 'TRANSFER_IN' || entry.entryType == 'TRANSFER_OUT';
    final bool isClickable = isPlantPayment || isRewardEntry || isSettlementEntry || isWithdrawalEntry || isTransferEntry;

    return GestureDetector(
      onTap: isClickable ? () => _showEntryDetail(entry) : null,
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.03),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            // 类型图标
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: isIncome
                    ? const Color(0x1A4CAF50)
                    : const Color(0x1AE53935),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(
                isIncome ? Icons.arrow_downward : Icons.arrow_upward,
                size: 20,
                color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
              ),
            ),
            const SizedBox(width: 12),
            // 类型和时间
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    entry.displayNameWithStatus(userHasNoPending: _userHasNoPending),
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF5D4037),
                    ),
                  ),
                  if (entry.sourceAccountFromMemo != null) ...[
                    const SizedBox(height: 2),
                    Text(
                      '来自 ${entry.sourceAccountFromMemo}',
                      style: const TextStyle(
                        fontSize: 11,
                        color: Color(0xFFD4AF37),
                      ),
                    ),
                  ],
                  const SizedBox(height: 4),
                  Text(
                    _formatDate(entry.createdAt),
                    style: const TextStyle(
                      fontSize: 10,
                      color: Color(0x995D4037),
                    ),
                  ),
                ],
              ),
            ),
            // 金额
            ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  FittedBox(
                    fit: BoxFit.scaleDown,
                    alignment: Alignment.centerRight,
                    child: Text(
                      '${isIncome ? '+' : ''}${_formatAmount(entry.amount)}',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w700,
                        color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                      ),
                    ),
                  ),
                  if (entry.balanceAfter != null) ...[
                    const SizedBox(height: 4),
                    FittedBox(
                      fit: BoxFit.scaleDown,
                      alignment: Alignment.centerRight,
                      child: Text(
                        '余额: ${_formatAmount(entry.balanceAfter!)}',
                        style: const TextStyle(
                          fontSize: 10,
                          color: Color(0x995D4037),
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            ),
            // 可点击时显示箭头
            if (isClickable) ...[
              const SizedBox(width: 8),
              const Icon(
                Icons.chevron_right,
                size: 20,
                color: Color(0x995D4037),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 显示流水详情（根据类型显示不同弹窗）
  void _showEntryDetail(LedgerEntry entry) {
    if (entry.entryType == 'PLANT_PAYMENT' && entry.refOrderId != null) {
      // 认种支付 - 显示合同详情
      _showTransactionDetail(entry);
    } else if (entry.entryType == 'REWARD_SETTLED') {
      // 结算 - 显示结算详情
      _showSettlementDetail(entry);
    } else if (entry.entryType == 'WITHDRAWAL') {
      // 提现 - 显示提现详情
      _showWithdrawalDetail(entry);
    } else if (entry.entryType == 'TRANSFER_IN' || entry.entryType == 'TRANSFER_OUT') {
      // 转入/转出 - 显示转账详情
      _showTransferDetail(entry);
    } else if (entry.allocationType != null) {
      // 权益分配 - 显示权益详情
      _showRewardDetail(entry);
    }
  }

  /// 显示转账详情弹窗（转入/转出）
  void _showTransferDetail(LedgerEntry entry) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _TransferDetailSheet(entry: entry),
    );
  }

  /// 显示提现详情弹窗
  void _showWithdrawalDetail(LedgerEntry entry) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _WithdrawalDetailSheet(
        entry: entry,
        walletService: ref.read(walletServiceProvider),
      ),
    );
  }

  /// 显示结算详情弹窗
  void _showSettlementDetail(LedgerEntry entry) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _SettlementDetailSheet(
        entry: entry,
        rewardService: ref.read(rewardServiceProvider),
      ),
    );
  }

  /// 显示交易详情弹窗（认种支付）
  Future<void> _showTransactionDetail(LedgerEntry entry) async {
    if (entry.refOrderId == null) return;

    final bool isPrePlanting = entry.refOrderId!.startsWith('PPL');

    // PPL 份额订单：查找是否已有对应的已签署合并合同
    String? signedMergeNo;
    if (isPrePlanting) {
      try {
        final merges = await ref.read(prePlantingServiceProvider).getMyMerges();
        final matched = merges.where(
          (m) => m.isSigned && m.sourceOrderNos.contains(entry.refOrderId),
        );
        if (matched.isNotEmpty) signedMergeNo = matched.first.mergeNo;
      } catch (_) {
        // 查不到就不显示合同按钮
      }
    }

    if (!mounted) return;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _TransactionDetailSheet(
        entry: entry,
        showContractButtons: !isPrePlanting || signedMergeNo != null,
        onViewContract: signedMergeNo != null
            ? () => _viewMergeContractPdf(signedMergeNo!)
            : isPrePlanting
                ? null
                : () => _viewContractPdf(entry.refOrderId!),
        onDownloadContract: signedMergeNo != null
            ? () => _downloadMergeContractPdf(signedMergeNo!)
            : isPrePlanting
                ? null
                : () => _downloadContractPdf(entry.refOrderId!),
      ),
    );
  }

  /// 显示权益详情弹窗
  void _showRewardDetail(LedgerEntry entry) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _RewardDetailSheet(entry: entry),
    );
  }

  /// 查看合同 PDF
  Future<void> _viewContractPdf(String orderNo) async {
    // 显示加载指示器
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
        ),
      ),
    );

    try {
      final contractService = ref.read(contractSigningServiceProvider);
      final pdfBytes = await contractService.downloadContractPdf(orderNo);

      // 保存到临时文件
      final tempDir = await getTemporaryDirectory();
      final pdfFile = File('${tempDir.path}/contract_$orderNo.pdf');
      await pdfFile.writeAsBytes(pdfBytes);

      if (!mounted) return;
      Navigator.of(context).pop(); // 关闭加载指示器

      // 打开 PDF 查看页面
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => _ContractPdfViewerPage(
            pdfPath: pdfFile.path,
            contractNo: orderNo,
          ),
        ),
      );
    } catch (e) {
      if (!mounted) return;
      Navigator.of(context).pop(); // 关闭加载指示器
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载合同失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 下载合同 PDF
  Future<void> _downloadContractPdf(String orderNo) async {
    // 显示加载指示器
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
        ),
      ),
    );

    try {
      final contractService = ref.read(contractSigningServiceProvider);
      final pdfBytes = await contractService.downloadContractPdf(orderNo);

      // 保存到下载目录
      final directory = await getApplicationDocumentsDirectory();
      final fileName = 'contract_$orderNo.pdf';
      final pdfFile = File('${directory.path}/$fileName');
      await pdfFile.writeAsBytes(pdfBytes);

      if (!mounted) return;
      Navigator.of(context).pop(); // 关闭加载指示器

      // 分享/保存文件
      await Share.shareXFiles(
        [XFile(pdfFile.path)],
        subject: '认种合同 - $orderNo',
      );
    } catch (e) {
      if (!mounted) return;
      Navigator.of(context).pop(); // 关闭加载指示器
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('下载合同失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 查看预种合并合同 PDF
  Future<void> _viewMergeContractPdf(String mergeNo) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
        ),
      ),
    );

    try {
      final prePlantingService = ref.read(prePlantingServiceProvider);
      final pdfBytes = await prePlantingService.downloadMergeContractPdf(mergeNo);

      final tempDir = await getTemporaryDirectory();
      final pdfFile = File('${tempDir.path}/merge_contract_$mergeNo.pdf');
      await pdfFile.writeAsBytes(pdfBytes);

      if (!mounted) return;
      Navigator.of(context).pop();

      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => _ContractPdfViewerPage(
            pdfPath: pdfFile.path,
            contractNo: mergeNo,
          ),
        ),
      );
    } catch (e) {
      if (!mounted) return;
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载合同失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 下载预种合并合同 PDF
  Future<void> _downloadMergeContractPdf(String mergeNo) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
        ),
      ),
    );

    try {
      final prePlantingService = ref.read(prePlantingServiceProvider);
      final pdfBytes = await prePlantingService.downloadMergeContractPdf(mergeNo);

      final directory = await getApplicationDocumentsDirectory();
      final fileName = 'merge_contract_$mergeNo.pdf';
      final pdfFile = File('${directory.path}/$fileName');
      await pdfFile.writeAsBytes(pdfBytes);

      if (!mounted) return;
      Navigator.of(context).pop();

      await Share.shareXFiles(
        [XFile(pdfFile.path)],
        subject: '预种合并合同 - $mergeNo',
      );
    } catch (e) {
      if (!mounted) return;
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('下载合同失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}

/// 交易详情底部弹窗
class _TransactionDetailSheet extends StatelessWidget {
  final LedgerEntry entry;
  final VoidCallback? onViewContract;
  final VoidCallback? onDownloadContract;
  final bool showContractButtons;

  const _TransactionDetailSheet({
    required this.entry,
    this.onViewContract,
    this.onDownloadContract,
    this.showContractButtons = true,
  });

  @override
  Widget build(BuildContext context) {
    final isIncome = entry.isIncome;

    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // 标题
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: isIncome
                          ? const Color(0x1A4CAF50)
                          : const Color(0x1AE53935),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(
                      Icons.description_outlined,
                      size: 24,
                      color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          entry.entryTypeName,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '订单号: ${entry.refOrderId ?? '-'}',
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0x995D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 分隔线
            Container(
              height: 1,
              color: const Color(0x1A8B5A2B),
            ),
            // 详情列表
            Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  _buildDetailRow('交易金额', '${isIncome ? '+' : ''}${_formatAmount(entry.amount)} 绿积分',
                      color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935)),
                  if (entry.balanceAfter != null)
                    _buildDetailRow('交易后余额', '${_formatAmount(entry.balanceAfter!)} 绿积分'),
                  _buildDetailRow('交易时间', _formatDateTime(entry.createdAt)),
                  if (entry.memo != null && entry.memo!.isNotEmpty)
                    _buildDetailRow('备注',
                        entry.refOrderId?.startsWith('PPL') == true ? '预种' : entry.memo!),
                ],
              ),
            ),
            // 合同操作按钮（仅认种支付显示，预种无合同）
            if (showContractButtons) ...[
              Container(
                height: 1,
                color: const Color(0x1A8B5A2B),
              ),
              Padding(
                padding: const EdgeInsets.all(20),
                child: Row(
                  children: [
                    Expanded(
                      child: OutlinedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          onViewContract?.call();
                        },
                        icon: const Icon(Icons.visibility_outlined, size: 18),
                        label: const Text('查看合同'),
                        style: OutlinedButton.styleFrom(
                          foregroundColor: const Color(0xFF5D4037),
                          side: const BorderSide(color: Color(0xFFD4AF37)),
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton.icon(
                        onPressed: () {
                          Navigator.of(context).pop();
                          onDownloadContract?.call();
                        },
                        icon: const Icon(Icons.download_outlined, size: 18),
                        label: const Text('下载合同'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFFD4AF37),
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {Color? color}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: color ?? const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  String _formatAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  String _formatDateTime(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }
}

/// 合同 PDF 查看页面
class _ContractPdfViewerPage extends StatelessWidget {
  final String pdfPath;
  final String contractNo;

  const _ContractPdfViewerPage({
    required this.pdfPath,
    required this.contractNo,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: const Text('认种合同'),
        backgroundColor: const Color(0xFFD4AF37),
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: PDFView(
        filePath: pdfPath,
        enableSwipe: true,
        swipeHorizontal: false,
        autoSpacing: true,
        pageFling: true,
        pageSnap: true,
        fitPolicy: FitPolicy.BOTH,
        onError: (error) {
          debugPrint('PDF 加载错误: $error');
        },
        onPageError: (page, error) {
          debugPrint('PDF 页面 $page 加载错误: $error');
        },
      ),
    );
  }
}

/// 权益详情底部弹窗
class _RewardDetailSheet extends StatelessWidget {
  final LedgerEntry entry;

  const _RewardDetailSheet({required this.entry});

  @override
  Widget build(BuildContext context) {
    final isIncome = entry.isIncome;

    // 根据权益类型获取图标
    IconData getRewardIcon() {
      switch (entry.allocationType) {
        case 'SHARE_RIGHT':
          return Icons.share_outlined;
        case 'PROVINCE_AREA_RIGHT':
        case 'PROVINCE_TEAM_RIGHT':
          return Icons.location_city_outlined;
        case 'CITY_AREA_RIGHT':
        case 'CITY_TEAM_RIGHT':
          return Icons.apartment_outlined;
        case 'COMMUNITY_RIGHT':
          return Icons.groups_outlined;
        default:
          return Icons.card_giftcard_outlined;
      }
    }

    // 根据权益类型获取描述
    String getRewardDescription() {
      switch (entry.allocationType) {
        case 'SHARE_RIGHT':
          return '通过分享邀请获得的权益收益';
        case 'PROVINCE_AREA_RIGHT':
          return '省级区域销售产生的权益收益';
        case 'PROVINCE_TEAM_RIGHT':
          return '省级团队业绩产生的权益收益';
        case 'CITY_AREA_RIGHT':
          return '市级区域销售产生的权益收益';
        case 'CITY_TEAM_RIGHT':
          return '市级团队业绩产生的权益收益';
        case 'COMMUNITY_RIGHT':
          return '社区运营产生的权益收益';
        default:
          return '权益分配收益';
      }
    }

    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // 标题区域
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: isIncome
                          ? const Color(0x1A4CAF50)
                          : const Color(0x1AE53935),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(
                      getRewardIcon(),
                      size: 24,
                      color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          entry.displayName,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          getRewardDescription(),
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0x995D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 分隔线
            Container(
              height: 1,
              color: const Color(0x1A8B5A2B),
            ),
            // 详情列表
            Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  _buildDetailRow(
                    '收益金额',
                    '${isIncome ? '+' : ''}${_formatAmount(entry.amount)} 绿积分',
                    color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                  ),
                  _buildDetailRow('权益类型', entry.displayName),
                  _buildDetailRow('流水类型', entry.entryTypeName),
                  if (entry.sourceAccountFromMemo != null)
                    _buildDetailRow('来源用户', entry.sourceAccountFromMemo!),
                  if (entry.balanceAfter != null)
                    _buildDetailRow('入账后余额', '${_formatAmount(entry.balanceAfter!)} 绿积分'),
                  _buildDetailRow('入账时间', _formatDateTime(entry.createdAt)),
                  if (entry.refOrderId != null && entry.refOrderId!.isNotEmpty)
                    _buildDetailRow('关联订单', entry.refOrderId!),
                  if (entry.memo != null && entry.memo!.isNotEmpty)
                    _buildDetailRow('备注', entry.memo!),
                ],
              ),
            ),
            // 底部关闭按钮
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('关闭'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {Color? color}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: color ?? const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  String _formatAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  String _formatDateTime(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }
}

/// 结算详情底部弹窗
class _SettlementDetailSheet extends StatefulWidget {
  final LedgerEntry entry;
  final RewardService rewardService;

  const _SettlementDetailSheet({
    required this.entry,
    required this.rewardService,
  });

  @override
  State<_SettlementDetailSheet> createState() => _SettlementDetailSheetState();
}

class _SettlementDetailSheetState extends State<_SettlementDetailSheet> {
  bool _isLoading = true;
  SettlementHistoryItem? _settlementDetail;

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

  /// 加载结算详情
  Future<void> _loadSettlementDetail() async {
    try {
      // 尝试从结算历史中查找匹配的记录
      final result = await widget.rewardService.getSettlementHistory(page: 1, pageSize: 50);

      // 尝试通过金额和时间匹配
      SettlementHistoryItem? matchedItem;
      for (final item in result.data) {
        // 比较金额（考虑浮点数精度）
        final amountMatch = (item.receivedAmount - widget.entry.amount).abs() < 0.01;
        // 比较时间（允许2分钟误差）
        final timeDiff = item.createdAt.difference(widget.entry.createdAt).inMinutes.abs();
        final timeMatch = timeDiff < 2;

        if (amountMatch && timeMatch) {
          matchedItem = item;
          break;
        }
      }

      if (mounted) {
        setState(() {
          _settlementDetail = matchedItem;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('[_SettlementDetailSheet] 加载结算详情失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // 标题区域
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: const Color(0x1A4CAF50),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(
                      Icons.check_circle_outline,
                      size: 24,
                      color: Color(0xFF4CAF50),
                    ),
                  ),
                  const SizedBox(width: 16),
                  const Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '结算详情',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '结算到钱包余额',
                          style: TextStyle(
                            fontSize: 12,
                            color: Color(0x995D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 分隔线
            Container(
              height: 1,
              color: const Color(0x1A8B5A2B),
            ),
            // 详情内容
            _isLoading
                ? const Padding(
                    padding: EdgeInsets.all(40),
                    child: Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                      ),
                    ),
                  )
                : Padding(
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      children: [
                        _buildDetailRow(
                          '结算金额',
                          '+${_formatAmount(widget.entry.amount)} 绿积分',
                          color: const Color(0xFF4CAF50),
                        ),
                        if (widget.entry.balanceAfter != null)
                          _buildDetailRow(
                            '结算后余额',
                            '${_formatAmount(widget.entry.balanceAfter!)} 绿积分',
                          ),
                        _buildDetailRow(
                          '结算时间',
                          _formatDateTime(widget.entry.createdAt),
                        ),
                        if (_settlementDetail != null) ...[
                          _buildDetailRow(
                            '涉及奖励',
                            '${_settlementDetail!.rewardEntryCount} 笔',
                          ),
                          _buildDetailRow(
                            '结算状态',
                            _settlementDetail!.statusName,
                            color: _settlementDetail!.status == 'SUCCESS'
                                ? const Color(0xFF4CAF50)
                                : const Color(0xFFFF9800),
                          ),
                        ],
                        if (widget.entry.memo != null && widget.entry.memo!.isNotEmpty)
                          _buildDetailRow('备注', widget.entry.memo!),
                      ],
                    ),
                  ),
            // 底部关闭按钮
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('关闭'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {Color? color}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: color ?? const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  String _formatAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  String _formatDateTime(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }
}

/// 提现详情底部弹窗
class _WithdrawalDetailSheet extends StatefulWidget {
  final LedgerEntry entry;
  final WalletService walletService;

  const _WithdrawalDetailSheet({
    required this.entry,
    required this.walletService,
  });

  @override
  State<_WithdrawalDetailSheet> createState() => _WithdrawalDetailSheetState();
}

class _WithdrawalDetailSheetState extends State<_WithdrawalDetailSheet> {
  bool _isLoading = true;
  WithdrawRecord? _withdrawalDetail;

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

  /// 加载提现详情
  Future<void> _loadWithdrawalDetail() async {
    try {
      // 获取提现记录列表
      final records = await widget.walletService.getWithdrawals();

      // 尝试通过金额和时间匹配
      WithdrawRecord? matchedRecord;
      for (final record in records) {
        // 比较金额（考虑浮点数精度，使用 netAmount 或 amount）
        final amountMatch = (record.netAmount - widget.entry.amount.abs()).abs() < 0.01 ||
                            (record.amount - widget.entry.amount.abs()).abs() < 0.01;
        // 比较时间（允许2分钟误差）
        final timeDiff = record.createdAt.difference(widget.entry.createdAt).inMinutes.abs();
        final timeMatch = timeDiff < 2;

        if (amountMatch && timeMatch) {
          matchedRecord = record;
          break;
        }
      }

      if (mounted) {
        setState(() {
          _withdrawalDetail = matchedRecord;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('[_WithdrawalDetailSheet] 加载提现详情失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // 标题区域
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: const Color(0x1AE53935),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(
                      Icons.arrow_upward,
                      size: 24,
                      color: Color(0xFFE53935),
                    ),
                  ),
                  const SizedBox(width: 16),
                  const Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '提现详情',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '提取到外部钱包',
                          style: TextStyle(
                            fontSize: 12,
                            color: Color(0x995D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 分隔线
            Container(
              height: 1,
              color: const Color(0x1A8B5A2B),
            ),
            // 详情内容
            _isLoading
                ? const Padding(
                    padding: EdgeInsets.all(40),
                    child: Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                      ),
                    ),
                  )
                : Padding(
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      children: [
                        _buildWithdrawalRow(
                          '提现金额',
                          '-${_formatWithdrawalAmount(widget.entry.amount.abs())} 绿积分',
                          color: const Color(0xFFE53935),
                        ),
                        if (widget.entry.balanceAfter != null)
                          _buildWithdrawalRow(
                            '提现后余额',
                            '${_formatWithdrawalAmount(widget.entry.balanceAfter!)} 绿积分',
                          ),
                        _buildWithdrawalRow(
                          '提现时间',
                          _formatWithdrawalDateTime(widget.entry.createdAt),
                        ),
                        if (_withdrawalDetail != null) ...[
                          _buildWithdrawalRow(
                            '订单编号',
                            _withdrawalDetail!.orderNo,
                          ),
                          _buildWithdrawalRow(
                            '提现状态',
                            _getWithdrawalStatusName(_withdrawalDetail!.status),
                            color: _getWithdrawalStatusColor(_withdrawalDetail!.status),
                          ),
                          _buildWithdrawalRow(
                            '提现网络',
                            _getWithdrawalChainName(_withdrawalDetail!.chainType),
                          ),
                          if (_withdrawalDetail!.fee > 0)
                            _buildWithdrawalRow(
                              '手续费',
                              '${_formatWithdrawalAmount(_withdrawalDetail!.fee)} 绿积分',
                            ),
                          _buildWithdrawalRow(
                            '到账地址',
                            _getWithdrawalShortAddress(_withdrawalDetail!.toAddress),
                          ),
                          // 交易哈希（已隐藏）
                          // if (_withdrawalDetail!.txHash != null &&
                          //     _withdrawalDetail!.txHash!.isNotEmpty)
                          //   _buildWithdrawalRow(
                          //     '交易哈希',
                          //     _getWithdrawalShortAddress(_withdrawalDetail!.txHash!),
                          //   ),
                        ],
                        if (widget.entry.memo != null && widget.entry.memo!.isNotEmpty)
                          _buildWithdrawalRow('备注', widget.entry.memo!),
                      ],
                    ),
                  ),
            // 底部关闭按钮
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('关闭'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWithdrawalRow(String label, String value, {Color? color}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: color ?? const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  String _formatWithdrawalAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  String _formatWithdrawalDateTime(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }

  String _getWithdrawalStatusName(String status) {
    switch (status) {
      case 'PENDING':
        return '待处理';
      case 'FROZEN':
        return '已冻结';
      case 'CONFIRMED':
        return '已确认';
      case 'COMPLETED':
        return '已完成';
      case 'FAILED':
        return '失败';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  }

  Color _getWithdrawalStatusColor(String status) {
    switch (status) {
      case 'COMPLETED':
        return const Color(0xFF4CAF50);
      case 'PENDING':
      case 'FROZEN':
      case 'CONFIRMED':
        return const Color(0xFFFF9800);
      case 'FAILED':
      case 'CANCELLED':
        return const Color(0xFFE53935);
      default:
        return const Color(0xFF5D4037);
    }
  }

  String _getWithdrawalChainName(String chainType) {
    switch (chainType) {
      case 'KAVA':
        return 'KAVA';
      case 'BSC':
        return 'BSC';
      case 'INTERNAL':
        return '内部划转';
      default:
        return chainType;
    }
  }

  String _getWithdrawalShortAddress(String address) {
    if (address.length <= 16) return address;
    return '${address.substring(0, 8)}...${address.substring(address.length - 6)}';
  }
}

/// 转账详情底部弹窗（转入/转出）
class _TransferDetailSheet extends StatelessWidget {
  final LedgerEntry entry;

  const _TransferDetailSheet({required this.entry});

  @override
  Widget build(BuildContext context) {
    final isTransferIn = entry.entryType == 'TRANSFER_IN';
    final isIncome = entry.isIncome;

    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: const Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // 标题区域
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: isIncome
                          ? const Color(0x1A4CAF50)
                          : const Color(0x1AE53935),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(
                      isTransferIn ? Icons.call_received : Icons.call_made,
                      size: 24,
                      color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          isTransferIn ? '转入详情' : '转出详情',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF5D4037),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          isTransferIn ? '来自其他用户的转账' : '转账给其他用户',
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0x995D4037),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 分隔线
            Container(
              height: 1,
              color: const Color(0x1A8B5A2B),
            ),
            // 详情内容
            Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  _buildTransferRow(
                    isTransferIn ? '转入金额' : '转出金额',
                    '${isIncome ? '+' : ''}${_formatTransferAmount(entry.amount)} 绿积分',
                    color: isIncome ? const Color(0xFF4CAF50) : const Color(0xFFE53935),
                  ),
                  if (entry.balanceAfter != null)
                    _buildTransferRow(
                      isTransferIn ? '转入后余额' : '转出后余额',
                      '${_formatTransferAmount(entry.balanceAfter!)} 绿积分',
                    ),
                  _buildTransferRow(
                    isTransferIn ? '转入时间' : '转出时间',
                    _formatTransferDateTime(entry.createdAt),
                  ),
                  // 对方账户信息
                  if (entry.counterpartyAccountSequence != null)
                    _buildTransferRow(
                      isTransferIn ? '来自账户' : '转至账户',
                      entry.counterpartyAccountSequence!,
                    ),
                  // 手续费（仅转出有）
                  if (entry.transferFee != null && entry.transferFee! > 0)
                    _buildTransferRow(
                      '手续费',
                      '${_formatTransferAmount(entry.transferFee!)} 绿积分',
                    ),
                  // 关联订单
                  if (entry.refOrderId != null && entry.refOrderId!.isNotEmpty)
                    _buildTransferRow('订单编号', entry.refOrderId!),
                  // 交易哈希（已隐藏）
                  // if (entry.refTxHash != null && entry.refTxHash!.isNotEmpty)
                  //   _buildTransferRow(
                  //     '交易哈希',
                  //     _getTransferShortAddress(entry.refTxHash!),
                  //   ),
                  // 备注
                  if (entry.memo != null && entry.memo!.isNotEmpty)
                    _buildTransferRow('备注', entry.memo!),
                ],
              ),
            ),
            // 底部关闭按钮
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('关闭'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTransferRow(String label, String value, {Color? color}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0x995D4037),
            ),
          ),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: color ?? const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  String _formatTransferAmount(double amount) {
    final formatter = NumberFormat('#,##0.00', 'zh_CN');
    return formatter.format(amount);
  }

  String _formatTransferDateTime(DateTime date) {
    return DateTimeUtils.formatDateTime(date);
  }

  String _getTransferShortAddress(String address) {
    if (address.length <= 16) return address;
    return '${address.substring(0, 8)}...${address.substring(address.length - 6)}';
  }
}
