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/planting_record.dart';
import '../../providers/user_providers.dart';
import '../../providers/mining_providers.dart';

/// 参与记录页面
class PlantingRecordsPage extends ConsumerStatefulWidget {
  const PlantingRecordsPage({super.key});

  @override
  ConsumerState<PlantingRecordsPage> createState() => _PlantingRecordsPageState();
}

class _PlantingRecordsPageState extends ConsumerState<PlantingRecordsPage> {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF22C55E);
  static const Color _blue = Color(0xFF3B82F6);
  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 = 10;

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

    final recordsParams = PlantingRecordsParams(
      accountSequence: accountSequence,
      page: _currentPage,
      pageSize: _pageSize,
    );
    final recordsAsync = ref.watch(plantingRecordsProvider(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(plantingRecordsProvider(recordsParams));
        },
        child: recordsAsync.when(
          loading: () => _buildLoadingView(),
          error: (error, stack) => _buildErrorView(error.toString(), recordsParams),
          data: (ledgerPage) {
            if (ledgerPage == null || ledgerPage.items.isEmpty) {
              return _buildEmptyView();
            }
            return _buildContent(ledgerPage);
          },
        ),
      ),
    );
  }

  Widget _buildLoadingView() {
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Column(
        children: [
          // 汇总卡片骨架
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: List.generate(3, (index) => _buildShimmerStat()),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: List.generate(3, (index) => _buildShimmerStat()),
                ),
              ],
            ),
          ),
          // 列表骨架
          ...List.generate(5, (index) => _buildShimmerCard()),
        ],
      ),
    );
  }

  Widget _buildShimmerStat() {
    return Column(
      children: [
        Container(
          width: 60,
          height: 24,
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(4),
          ),
        ),
        const SizedBox(height: 4),
        Container(
          width: 40,
          height: 12,
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(4),
          ),
        ),
      ],
    );
  }

  Widget _buildShimmerCard() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 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: 100, height: 16, color: Colors.grey[300]),
              Container(width: 60, height: 20, color: Colors.grey[300]),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Container(width: 80, height: 12, color: Colors.grey[300]),
              const SizedBox(width: 16),
              Container(width: 80, height: 12, color: Colors.grey[300]),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error, PlantingRecordsParams 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(plantingRecordsProvider(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.eco_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 _buildContent(PlantingLedgerPage ledgerPage) {
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Column(
        children: [
          // 汇总卡片
          _buildSummaryCard(ledgerPage.summary),
          // 记录列表
          ...ledgerPage.items.map((record) => _buildRecordCard(record)),
          // 分页信息
          _buildPaginationInfo(ledgerPage),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildSummaryCard(PlantingSummary summary) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.eco, size: 20, color: _green),
              const SizedBox(width: 8),
              const Text(
                '参与汇总',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: _darkText,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('总订单数', summary.totalOrders.toString()),
              _buildSummaryItem('总参与量', summary.totalTreeCount.toString(), color: _green),
              _buildSummaryItem('总贡献值', formatAmount(summary.effectiveContribution), color: _orange),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('有效参与', summary.effectiveTreeCount.toString(), color: _blue),
              _buildSummaryItem(
                '首次参与',
                summary.firstPlantingAt != null
                    ? DateFormat('MM-dd').format(summary.firstPlantingAt!.toLocal())
                    : '-',
              ),
              _buildSummaryItem(
                '最近参与',
                summary.lastPlantingAt != null
                    ? DateFormat('MM-dd').format(summary.lastPlantingAt!.toLocal())
                    : '-',
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryItem(String label, String value, {Color? color}) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color ?? _darkText,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(fontSize: 12, color: _grayText),
        ),
      ],
    );
  }

  Widget _buildRecordCard(PlantingRecord record) {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: !record.isActive
            ? Border.all(color: Colors.grey.withOpacity(0.3))
            : null,
      ),
      child: Opacity(
        opacity: record.isActive ? 1.0 : 0.6,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 第一行：订单号 + 状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    record.originalAdoptionId ?? record.orderNo,
                    style: const TextStyle(
                      fontSize: 13,
                      color: _darkText,
                      fontFamily: 'monospace',
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 8),
                _buildStatusBadge(record.status),
              ],
            ),
            const SizedBox(height: 12),

            // 第二行：参与数量 + 单个贡献值 + 总贡献值
            Wrap(
              spacing: 12,
              runSpacing: 8,
              children: [
                _buildInfoItem('参与数量', '${record.treeCount}个'),
                _buildInfoItem('单个贡献值', formatAmount(record.contributionPerTree)),
                _buildInfoItem('总贡献值', formatAmount(record.totalContribution), isHighlight: true),
              ],
            ),
            const SizedBox(height: 8),

            // 第三行：参与日期
            Row(
              children: [
                Icon(Icons.calendar_today_outlined, size: 12, color: _grayText.withOpacity(0.7)),
                const SizedBox(width: 4),
                Text(
                  record.adoptionDate != null
                      ? DateFormat('yyyy-MM-dd HH:mm').format(record.adoptionDate!.toLocal())
                      : DateFormat('yyyy-MM-dd HH:mm').format(record.createdAt.toLocal()),
                  style: TextStyle(fontSize: 11, color: _grayText.withOpacity(0.7)),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge(PlantingStatus status) {
    Color bgColor;
    Color textColor;

    switch (status) {
      case PlantingStatus.miningEnabled:
        bgColor = _green.withOpacity(0.1);
        textColor = _green;
        break;
      case PlantingStatus.paid:
      case PlantingStatus.fundAllocated:
        bgColor = _blue.withOpacity(0.1);
        textColor = _blue;
        break;
      case PlantingStatus.created:
        bgColor = _orange.withOpacity(0.1);
        textColor = _orange;
        break;
      case PlantingStatus.cancelled:
      case PlantingStatus.expired:
        bgColor = Colors.red.withOpacity(0.1);
        textColor = Colors.red;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        status.toString().split('.').last == 'miningEnabled' ? '已开始' : _getStatusText(status),
        style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: textColor),
      ),
    );
  }

  String _getStatusText(PlantingStatus status) {
    switch (status) {
      case PlantingStatus.created:
        return '已创建';
      case PlantingStatus.paid:
        return '已支付';
      case PlantingStatus.fundAllocated:
        return '资金已分配';
      case PlantingStatus.miningEnabled:
        return '已开始';
      case PlantingStatus.cancelled:
        return '已取消';
      case PlantingStatus.expired:
        return '已过期';
    }
  }

  Widget _buildInfoItem(String label, String value, {bool isHighlight = false}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          '$label: ',
          style: TextStyle(fontSize: 12, color: _grayText.withOpacity(0.7)),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 12,
            color: isHighlight ? _green : _darkText,
            fontWeight: isHighlight ? FontWeight.w600 : FontWeight.w500,
          ),
        ),
      ],
    );
  }

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

    if (totalPages <= 1) {
      return const SizedBox.shrink();
    }

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Column(
        children: [
          Text(
            '共 ${ledgerPage.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),
                ),
            ],
          ),
        ],
      ),
    );
  }
}
