import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/utils/format_utils.dart';
import '../../../domain/entities/mining_record.dart';
import '../../../domain/repositories/mining_repository.dart';
import '../../providers/user_providers.dart';
import '../../providers/mining_providers.dart';

/// 分配记录页面（挖矿记录）
class MiningRecordsListPage extends ConsumerStatefulWidget {
  const MiningRecordsListPage({super.key});

  @override
  ConsumerState<MiningRecordsListPage> createState() => _MiningRecordsListPageState();
}

class _MiningRecordsListPageState extends ConsumerState<MiningRecordsListPage> {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF22C55E);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _bgGray = Color(0xFFF3F4F6);

  int _currentPage = 1;
  static const int _pageSize = 20;

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userNotifierProvider);
    final accountSequence = user.accountSequence ?? '';

    final recordsParams = MiningRecordsParams(
      accountSequence: accountSequence,
      page: _currentPage,
      pageSize: _pageSize,
    );
    final recordsAsync = ref.watch(miningRecordsProvider(recordsParams));

    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: _darkText, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '分配记录',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: _darkText,
          ),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          setState(() => _currentPage = 1);
          ref.invalidate(miningRecordsProvider(recordsParams));
        },
        child: recordsAsync.when(
          loading: () => _buildLoadingList(),
          error: (error, stack) => _buildErrorView(error.toString(), recordsParams),
          data: (recordsPage) {
            if (recordsPage == null || recordsPage.items.isEmpty) {
              return _buildEmptyView();
            }
            return _buildRecordsList(recordsPage);
          },
        ),
      ),
    );
  }

  Widget _buildLoadingList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: 10,
      itemBuilder: (context, index) => _buildShimmerCard(),
    );
  }

  Widget _buildShimmerCard() {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 120,
                height: 16,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              Container(
                width: 80,
                height: 20,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Container(
                width: 60,
                height: 12,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              const SizedBox(width: 16),
              Container(
                width: 80,
                height: 12,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error, MiningRecordsParams params) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 48, color: AppColors.error),
          const SizedBox(height: 16),
          Text('加载失败', style: TextStyle(fontSize: 16, color: _grayText)),
          const SizedBox(height: 8),
          Text(error, style: TextStyle(fontSize: 12, color: _grayText)),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              ref.invalidate(miningRecordsProvider(params));
            },
            style: ElevatedButton.styleFrom(backgroundColor: _orange),
            child: const Text('重试', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.inbox_outlined, size: 64, color: _grayText.withOpacity(0.5)),
          const SizedBox(height: 16),
          Text(
            '暂无分配记录',
            style: TextStyle(fontSize: 16, color: _grayText),
          ),
          const SizedBox(height: 8),
          Text(
            '参与后将开始产生收益',
            style: TextStyle(fontSize: 14, color: _grayText.withOpacity(0.7)),
          ),
        ],
      ),
    );
  }

  Widget _buildRecordsList(MiningRecordsPage recordsPage) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: recordsPage.items.length + 1,
      itemBuilder: (context, index) {
        if (index == recordsPage.items.length) {
          return _buildPaginationInfo(recordsPage);
        }
        return _buildRecordCard(recordsPage.items[index]);
      },
    );
  }

  Widget _buildRecordCard(MiningRecord record) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第一行：分配时间 + 获得积分股
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                _shortTime(record.distributionMinute),
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                  color: _darkText,
                ),
              ),
              Flexible(
                child: Text(
                  '+${formatDecimal(record.shareAmount, 13)}',
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                    color: _green,
                    fontFamily: 'monospace',
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),

          // 第二行：贡献值占比 + 价格快照
          Row(
            children: [
              Expanded(
                child: _buildInfoItem('贡献值占比', _formatPercent(record.contributionRatio)),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: _buildInfoItem('价格快照', _formatPrice(record.priceSnapshot)),
              ),
            ],
          ),
          const SizedBox(height: 8),

          // 第三行：记录时间
          Row(
            children: [
              Icon(Icons.access_time, size: 12, color: _grayText.withOpacity(0.7)),
              const SizedBox(width: 4),
              Text(
                DateFormat('yyyy-MM-dd HH:mm:ss').format(record.createdAt.toLocal()),
                style: TextStyle(fontSize: 11, color: _grayText.withOpacity(0.7)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoItem(String label, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          '$label: ',
          style: TextStyle(fontSize: 12, color: _grayText.withOpacity(0.7)),
        ),
        Flexible(
          child: Text(
            value,
            style: const TextStyle(
              fontSize: 12,
              color: _darkText,
              fontWeight: FontWeight.w500,
              fontFamily: 'monospace',
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  /// 压缩时间显示：'2026-03-02 17:24:00' → '26/03/02 17:24'
  String _shortTime(String time) {
    // 去掉秒和毫秒部分，截短年份
    final t = time.replaceAll('T', ' ').split('.').first; // 去毫秒
    try {
      // distributionMinute 从后端返回的是 UTC 时间但不带 Z 后缀,
      // DateTime.parse 不带 Z 会当作本地时间, 需要追加 Z 标记为 UTC
      final utcStr = t.endsWith('Z') ? t : '${t}Z';
      final dt = DateTime.parse(utcStr).toLocal();
      final y = (dt.year % 100).toString().padLeft(2, '0');
      final m = dt.month.toString().padLeft(2, '0');
      final d = dt.day.toString().padLeft(2, '0');
      final h = dt.hour.toString().padLeft(2, '0');
      final min = dt.minute.toString().padLeft(2, '0');
      final s = dt.second.toString().padLeft(2, '0');
      return '$y/$m/$d $h:$min:$s';
    } catch (_) {
      return time.length > 16 ? time.substring(0, 16) : time;
    }
  }

  String _formatPercent(String ratio) {
    try {
      final value = double.parse(ratio);
      return '${(value * 100).toStringAsFixed(6)}%';
    } catch (e) {
      return ratio;
    }
  }

  String _formatPrice(String price) {
    try {
      final value = double.parse(price);
      if (value >= 1) return value.toStringAsFixed(4);
      if (value >= 0.0001) return value.toStringAsFixed(6);
      if (value <= 0) return '0';
      // 0.00000980 → 0.0{5}980
      final str = value.toStringAsFixed(18);
      final dotIndex = str.indexOf('.');
      int zeroCount = 0;
      for (int i = dotIndex + 1; i < str.length; i++) {
        if (str[i] == '0') {
          zeroCount++;
        } else {
          break;
        }
      }
      final sigStart = dotIndex + 1 + zeroCount;
      final sigEnd = sigStart + 7 > str.length ? str.length : sigStart + 7;
      final significant = str.substring(sigStart, sigEnd);
      return '0.0{$zeroCount}$significant';
    } catch (e) {
      return price;
    }
  }

  Widget _buildPaginationInfo(MiningRecordsPage recordsPage) {
    final totalPages = recordsPage.totalPages > 0
        ? recordsPage.totalPages
        : (recordsPage.total / _pageSize).ceil();

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Column(
        children: [
          Text(
            '共 ${recordsPage.total} 条记录，第 $_currentPage / $totalPages 页',
            style: TextStyle(fontSize: 12, color: _grayText),
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (_currentPage > 1)
                TextButton.icon(
                  onPressed: () {
                    setState(() => _currentPage--);
                  },
                  icon: const Icon(Icons.chevron_left, size: 18),
                  label: const Text('上一页'),
                  style: TextButton.styleFrom(foregroundColor: _orange),
                ),
              const SizedBox(width: 16),
              if (_currentPage < totalPages)
                TextButton.icon(
                  onPressed: () {
                    setState(() => _currentPage++);
                  },
                  icon: const Text('下一页'),
                  label: const Icon(Icons.chevron_right, size: 18),
                  style: TextButton.styleFrom(foregroundColor: _orange),
                ),
            ],
          ),
        ],
      ),
    );
  }
}
