import 'package:flutter/material.dart';

/// 可折叠卡片列表组件
/// 用于显示待领取奖励等明细列表，只有选中的卡片展开，其他折叠显示摘要
class CollapsibleCardList<T> extends StatefulWidget {
  /// 数据列表
  final List<T> items;

  /// 构建展开状态的卡片
  final Widget Function(T item) expandedBuilder;

  /// 构建折叠状态的卡片摘要
  final Widget Function(T item) collapsedBuilder;

  /// 展开卡片的高度
  final double expandedHeight;

  /// 折叠卡片的高度
  final double collapsedHeight;

  /// 容器最大高度
  final double maxHeight;

  /// 选中索引变化回调
  final ValueChanged<int>? onSelectedIndexChanged;

  const CollapsibleCardList({
    super.key,
    required this.items,
    required this.expandedBuilder,
    required this.collapsedBuilder,
    this.expandedHeight = 110,
    this.collapsedHeight = 44,
    this.maxHeight = 280,
    this.onSelectedIndexChanged,
  });

  @override
  State<CollapsibleCardList<T>> createState() => _CollapsibleCardListState<T>();
}

class _CollapsibleCardListState<T> extends State<CollapsibleCardList<T>> {
  int _selectedIndex = 0;
  final ScrollController _scrollController = ScrollController();

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

  void _selectCard(int index) {
    if (index == _selectedIndex) return;

    setState(() {
      _selectedIndex = index;
    });

    widget.onSelectedIndexChanged?.call(index);

    // 滚动确保选中的卡片可见
    _scrollToSelected(index);
  }

  void _scrollToSelected(int index) {
    if (!_scrollController.hasClients) return;

    // 计算选中卡片的位置
    double offset = 0;
    for (int i = 0; i < index; i++) {
      offset += i == _selectedIndex ? widget.expandedHeight : widget.collapsedHeight;
      offset += 6; // 间距
    }

    // 确保在可视范围内
    final viewportHeight = _scrollController.position.viewportDimension;
    final maxScroll = _scrollController.position.maxScrollExtent;

    if (offset < _scrollController.offset) {
      _scrollController.animateTo(
        offset,
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOutCubic,
      );
    } else if (offset + widget.expandedHeight > _scrollController.offset + viewportHeight) {
      _scrollController.animateTo(
        (offset + widget.expandedHeight - viewportHeight).clamp(0, maxScroll),
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeOutCubic,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.items.isEmpty) {
      return const SizedBox.shrink();
    }

    // 计算内容总高度
    final contentHeight = widget.expandedHeight +
        (widget.items.length - 1) * widget.collapsedHeight +
        (widget.items.length - 1) * 6; // 间距

    // 使用 ConstrainedBox 限制最大高度
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxHeight: contentHeight.clamp(0, widget.maxHeight),
      ),
      child: ListView.separated(
        controller: _scrollController,
        shrinkWrap: true,
        physics: contentHeight > widget.maxHeight
            ? const ClampingScrollPhysics()
            : const NeverScrollableScrollPhysics(),
        itemCount: widget.items.length,
        separatorBuilder: (context, index) => const SizedBox(height: 6),
        itemBuilder: (context, index) {
          final isSelected = index == _selectedIndex;
          final item = widget.items[index];

          return GestureDetector(
            onTap: () => _selectCard(index),
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              curve: Curves.easeOutCubic,
              height: isSelected ? widget.expandedHeight : widget.collapsedHeight,
              decoration: BoxDecoration(
                color: isSelected ? Colors.white : const Color(0xFFFFFDF8),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: isSelected ? const Color(0x44D4AF37) : const Color(0x22D4AF37),
                  width: isSelected ? 1.5 : 1,
                ),
              ),
              clipBehavior: Clip.antiAlias,
              child: isSelected
                  ? widget.expandedBuilder(item)
                  : widget.collapsedBuilder(item),
            ),
          );
        },
      ),
    );
  }
}

/// 带索引指示器的可折叠卡片列表
class IndexedCollapsibleCardList<T> extends StatefulWidget {
  /// 数据列表
  final List<T> items;

  /// 构建展开状态的卡片
  final Widget Function(T item) expandedBuilder;

  /// 构建折叠状态的卡片摘要
  final Widget Function(T item) collapsedBuilder;

  /// 展开卡片的高度
  final double expandedHeight;

  /// 折叠卡片的高度
  final double collapsedHeight;

  /// 容器最大高度
  final double maxHeight;

  const IndexedCollapsibleCardList({
    super.key,
    required this.items,
    required this.expandedBuilder,
    required this.collapsedBuilder,
    this.expandedHeight = 110,
    this.collapsedHeight = 44,
    this.maxHeight = 280,
  });

  @override
  State<IndexedCollapsibleCardList<T>> createState() =>
      _IndexedCollapsibleCardListState<T>();
}

class _IndexedCollapsibleCardListState<T>
    extends State<IndexedCollapsibleCardList<T>> {
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    if (widget.items.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 卡片列表
        CollapsibleCardList<T>(
          items: widget.items,
          expandedBuilder: widget.expandedBuilder,
          collapsedBuilder: widget.collapsedBuilder,
          expandedHeight: widget.expandedHeight,
          collapsedHeight: widget.collapsedHeight,
          maxHeight: widget.maxHeight,
          onSelectedIndexChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
        ),
        // 索引指示器
        if (widget.items.length > 1) ...[
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(
              widget.items.length,
              (index) => Container(
                width: index == _selectedIndex ? 16 : 6,
                height: 6,
                margin: const EdgeInsets.symmetric(horizontal: 2),
                decoration: BoxDecoration(
                  color: index == _selectedIndex
                      ? const Color(0xFFD4AF37)
                      : const Color(0x33D4AF37),
                  borderRadius: BorderRadius.circular(3),
                ),
              ),
            ),
          ),
        ],
      ],
    );
  }
}

// 保留旧的 StackedCardsView 以备兼容
/// 带堆叠效果的卡片堆叠组件（使用 Stack 实现）
/// 注意：此组件可能会超出容器范围，建议使用 CollapsibleCardList
class StackedCardsView<T> extends StatefulWidget {
  /// 数据列表
  final List<T> items;

  /// 构建单个卡片的方法
  final Widget Function(T item, bool isSelected, int index) itemBuilder;

  /// 卡片露出的高度
  final double peekHeight;

  /// 展开的卡片高度
  final double expandedCardHeight;

  /// 是否启用声音反馈
  final bool enableSound;

  /// 选中索引变化回调
  final ValueChanged<int>? onSelectedIndexChanged;

  const StackedCardsView({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.peekHeight = 24,
    this.expandedCardHeight = 120,
    this.enableSound = true,
    this.onSelectedIndexChanged,
  });

  @override
  State<StackedCardsView<T>> createState() => _StackedCardsViewState<T>();
}

class _StackedCardsViewState<T> extends State<StackedCardsView<T>> {
  int _selectedIndex = 0;

  void _selectCard(int index) {
    if (index == _selectedIndex) return;

    setState(() {
      _selectedIndex = index;
    });

    widget.onSelectedIndexChanged?.call(index);
  }

  @override
  Widget build(BuildContext context) {
    if (widget.items.isEmpty) {
      return const SizedBox.shrink();
    }

    // 使用 CollapsibleCardList 替代 Stack 实现
    return CollapsibleCardList<T>(
      items: widget.items,
      expandedHeight: widget.expandedCardHeight,
      collapsedHeight: widget.peekHeight + 20,
      maxHeight: 280,
      expandedBuilder: (item) {
        final index = widget.items.indexOf(item);
        return widget.itemBuilder(item, true, index);
      },
      collapsedBuilder: (item) {
        final index = widget.items.indexOf(item);
        return widget.itemBuilder(item, false, index);
      },
      onSelectedIndexChanged: widget.onSelectedIndexChanged,
    );
  }
}
