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

/// Type alias to avoid name conflict with page class
typedef RecordsPageData = ContributionRecordsPage;

/// 贡献值记录完整列表页面
class ContributionRecordsListPage extends ConsumerStatefulWidget {
  const ContributionRecordsListPage({super.key});

  @override
  ConsumerState<ContributionRecordsListPage> createState() => _ContributionRecordsListPageState();
}

class _ContributionRecordsListPageState extends ConsumerState<ContributionRecordsListPage> {
  // 设计色彩
  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;

  // 筛选条件
  ContributionSourceType? _selectedSourceType;

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

    final recordsParams = ContributionRecordsParams(
      accountSequence: accountSequence,
      page: _currentPage,
      pageSize: _pageSize,
      sourceType: _selectedSourceType,
    );
    final recordsAsync = ref.watch(contributionRecordsProvider(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: Column(
        children: [
          // 筛选栏
          _buildFilterBar(),
          // 列表
          Expanded(
            child: RefreshIndicator(
              onRefresh: () async {
                setState(() => _currentPage = 1);
                ref.invalidate(contributionRecordsProvider(recordsParams));
              },
              child: recordsAsync.when(
                loading: () => _buildLoadingList(),
                error: (error, stack) => _buildErrorView(error.toString()),
                data: (recordsPage) {
                  if (recordsPage == null || recordsPage.data.isEmpty) {
                    return _buildEmptyView();
                  }
                  return _buildRecordsList(recordsPage, accountSequence);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Row(
          children: [
            _buildFilterChip('全部', null),
            const SizedBox(width: 8),
            _buildFilterChip('本人', ContributionSourceType.personal),
            const SizedBox(width: 8),
            _buildFilterChip('同伴下贡献值', ContributionSourceType.teamLevel),
            const SizedBox(width: 8),
            _buildFilterChip('同伴上贡献值', ContributionSourceType.teamBonus),
          ],
        ),
      ),
    );
  }

  Widget _buildFilterChip(String label, ContributionSourceType? type) {
    final isSelected = _selectedSourceType == type;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedSourceType = type;
          _currentPage = 1;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? _orange : _bgGray,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 13,
            color: isSelected ? Colors.white : _grayText,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  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: const [
              ShimmerBox(width: 80, height: 24),
              ShimmerBox(width: 100, height: 20),
            ],
          ),
          const SizedBox(height: 12),
          const ShimmerBox(width: 150, height: 14),
          const SizedBox(height: 8),
          Row(
            children: const [
              ShimmerBox(width: 60, height: 12),
              SizedBox(width: 16),
              ShimmerBox(width: 80, height: 12),
              SizedBox(width: 16),
              ShimmerBox(width: 60, height: 12),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error) {
    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: () {
              final user = ref.read(userNotifierProvider);
              final accountSequence = user.accountSequence ?? '';
              ref.invalidate(contributionRecordsProvider(ContributionRecordsParams(
                accountSequence: accountSequence,
                page: _currentPage,
                pageSize: _pageSize,
                sourceType: _selectedSourceType,
              )));
            },
            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(RecordsPageData recordsPage, String currentAccountSequence) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: recordsPage.data.length + 1, // +1 for pagination info
      itemBuilder: (context, index) {
        if (index == recordsPage.data.length) {
          return _buildPaginationInfo(recordsPage);
        }
        return _buildRecordCard(recordsPage.data[index], currentAccountSequence);
      },
    );
  }

  Widget _buildRecordCard(ContributionRecord record, String currentAccountSequence) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: record.isExpired
            ? Border.all(color: Colors.grey.withOpacity(0.3))
            : null,
      ),
      child: Opacity(
        opacity: record.isExpired ? 0.6 : 1.0,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 第一行：来源类型 + 获得贡献值
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    _buildSourceTypeBadge(record.sourceType),
                    const SizedBox(width: 8),
                    if (record.levelDepth != null)
                      _buildLevelBadge('L${record.levelDepth}')
                    else if (record.bonusTier != null)
                      _buildLevelBadge('T${record.bonusTier}'),
                  ],
                ),
                Text(
                  '+${formatAmount(record.finalContribution)}',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: record.isExpired ? _grayText : _green,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // 第二行：来源用户（同伴上贡献值不显示ID，因为都是自己种的树）
            if (record.sourceType != ContributionSourceType.teamBonus)
              Row(
                children: [
                  Icon(Icons.person_outline, size: 14, color: _grayText),
                  const SizedBox(width: 4),
                  Text(
                    record.sourceType == ContributionSourceType.personal
                        ? '本人参与'
                        : record.sourceAccountSequence ?? '未知用户',
                    style: TextStyle(fontSize: 13, color: _grayText),
                  ),
                ],
              ),
            const SizedBox(height: 8),

            // 第三行：详细信息
            Wrap(
              spacing: 16,
              runSpacing: 4,
              children: [
                _buildInfoItem('棵数', '${record.treeCount}'),
                _buildInfoItem('基础贡献值', formatAmount(record.baseContribution)),
                _buildInfoItem('分配比例', _formatPercent(record.distributionRate)),
              ],
            ),
            const SizedBox(height: 8),

            // 第四行：日期信息
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      Icon(Icons.calendar_today_outlined, size: 12, color: _grayText.withOpacity(0.7)),
                      const SizedBox(width: 4),
                      Text(
                        '生效: ${DateFormat('yyyy-MM-dd').format(record.effectiveDate.toLocal())}',
                        style: TextStyle(fontSize: 11, color: _grayText.withOpacity(0.7)),
                      ),
                    ],
                  ),
                ),
                Row(
                  children: [
                    Icon(
                      record.isExpired ? Icons.event_busy_outlined : Icons.event_available_outlined,
                      size: 12,
                      color: record.isExpired ? Colors.red.withOpacity(0.7) : _grayText.withOpacity(0.7),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '过期: ${DateFormat('yyyy-MM-dd').format(record.expireDate.toLocal())}',
                      style: TextStyle(
                        fontSize: 11,
                        color: record.isExpired ? Colors.red.withOpacity(0.7) : _grayText.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ],
            ),

            // 状态标签
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: BoxDecoration(
                color: record.isExpired
                    ? Colors.red.withOpacity(0.1)
                    : Colors.green.withOpacity(0.1),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                record.isExpired ? '无效' : '有效',
                style: TextStyle(
                  fontSize: 10,
                  color: record.isExpired ? Colors.red : Colors.green,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSourceTypeBadge(ContributionSourceType type) {
    String label;
    Color bgColor;
    Color textColor;

    switch (type) {
      case ContributionSourceType.personal:
        label = '本人参与';
        bgColor = _orange.withOpacity(0.1);
        textColor = _orange;
        break;
      case ContributionSourceType.teamLevel:
        label = '同伴下贡献值';
        bgColor = Colors.blue.withOpacity(0.1);
        textColor = Colors.blue;
        break;
      case ContributionSourceType.teamBonus:
        label = '同伴上贡献值';
        bgColor = Colors.purple.withOpacity(0.1);
        textColor = Colors.purple;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        label,
        style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: textColor),
      ),
    );
  }

  Widget _buildLevelBadge(String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: _bgGray,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        label,
        style: TextStyle(fontSize: 11, color: _grayText, fontWeight: FontWeight.w500),
      ),
    );
  }

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

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

  Widget _buildPaginationInfo(RecordsPageData recordsPage) {
    final 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),
                ),
            ],
          ),
        ],
      ),
    );
  }
}

/// Shimmer box widget for loading state
class ShimmerBox extends StatelessWidget {
  final double width;
  final double height;

  const ShimmerBox({
    super.key,
    required this.width,
    required this.height,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: Colors.grey[300],
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
}
