import React, {memo} from 'react';
import {
  FlatList,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {MetaPreview} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';
import Card from './Card';
import LoadingSpinner from './LoadingSpinner';

interface RowProps {
  title: string;
  items: MetaPreview[];
  loading?: boolean;
  onPressSeeAll?: () => void;
  onPressItem: (item: MetaPreview) => void;
  onEndReached?: () => void;
}

const Row = memo(function Row({
  title,
  items,
  loading,
  onPressSeeAll,
  onPressItem,
  onEndReached,
}: RowProps) {
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>{title}</Text>
        {onPressSeeAll && (
          <TouchableOpacity onPress={onPressSeeAll}>
            <Text style={styles.seeAll}>See All</Text>
          </TouchableOpacity>
        )}
      </View>
      {loading && items.length === 0 ? (
        <View style={styles.loadingContainer}>
          <LoadingSpinner size="small" />
        </View>
      ) : (
        <FlatList
          data={items}
          horizontal
          showsHorizontalScrollIndicator={false}
          keyExtractor={item => item.id}
          renderItem={({item}) => (
            <Card item={item} onPress={onPressItem} />
          )}
          contentContainerStyle={styles.list}
          onEndReached={onEndReached}
          onEndReachedThreshold={0.5}
          initialNumToRender={8}
          maxToRenderPerBatch={5}
          windowSize={3}
          removeClippedSubviews
        />
      )}
    </View>
  );
});

export default Row;

const styles = StyleSheet.create({
  container: {
    marginBottom: 24,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    marginBottom: 12,
  },
  title: {
    ...typography.subtitle,
    color: colors.textPrimary,
  },
  seeAll: {
    ...typography.caption,
    color: colors.primary,
  },
  list: {
    paddingHorizontal: 16,
  },
  loadingContainer: {
    height: 180,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
