import { View } from '@tarojs/components';
import { ReactNode } from 'react';
import EmptyState from '../../EmptyState';
import ErrorState from '../../ErrorState';
import LoadingCard from '../../ui/LoadingCard';
import './index.scss';

interface CardListProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => ReactNode;
  keyExtractor: (item: T) => string;
  loading?: boolean;
  error?: string | null;
  emptyText?: string;
  emptyAction?: { text: string; onPress: () => void };
  gap?: 'sm' | 'md';
}

function CardList<T>({
  items,
  renderItem,
  keyExtractor,
  loading = false,
  error = null,
  emptyText = '暂无数据',
  emptyAction,
  gap = 'md',
}: CardListProps<T>) {
  if (loading) {
    return <LoadingCard count={3} layout="card" />;
  }

  if (error) {
    return (
      <ErrorState
        text={error}
      />
    );
  }

  if (items.length === 0) {
    return (
      <EmptyState
        text={emptyText}
        actionText={emptyAction?.text}
        onAction={emptyAction?.onPress}
      />
    );
  }

  return (
    <View className={`card-list card-list--${gap}`}>
      {items.map((item, index) => (
        <View key={keyExtractor(item)} className="card-list__item">
          {renderItem(item, index)}
        </View>
      ))}
    </View>
  );
}

export default CardList;
