import React, { forwardRef, useContext } from 'react';
import { FlatList, FlatListProps, View } from 'react-native';
import Item from './Item';
import { GridContext } from './index';
import styles from './styles';
import { SpanNumber } from './types';

export interface ItemListProps extends FlatListProps<any> {
  /**
   * Represents the width of the Card component in terms of span numbers (1-12).
   */
  widthSpan?: SpanNumber;
  data: any[];
}

const ItemList = forwardRef(
  (
    {
      renderItem,
      widthSpan,
      style,
      contentContainerStyle,
      ...props
    }: ItemListProps,
    ref,
  ) => {
    const { gutterSize, numberOfColumns } = useContext(GridContext);
    const widthItem = (widthSpan ?? numberOfColumns) as SpanNumber;
    const numColumns = Math.floor(numberOfColumns / widthItem);
    const indexBegin = props?.data?.map(
      (_i: any, index: number) => index * numColumns,
    );
    const _renderItem = (item: any) => {
      if (indexBegin?.includes(item?.index)) {
        return <Item widthSpan={widthItem}>{renderItem?.(item)}</Item>;
      }
      return (
        <View style={{ paddingLeft: gutterSize }}>
          <Item widthSpan={widthItem}>{renderItem?.(item)}</Item>
        </View>
      );
    };

    return (
      <FlatList
        ref={ref as React.RefObject<FlatList>}
        {...props}
        key={`ItemList-${numColumns}`}
        keyExtractor={
          // prefer caller's keyExtractor; fallback to common id/key/index
          (props as any)?.keyExtractor ??
          ((item: any, index: number) =>
            (item?.id ?? item?.key ?? index).toString())
        }
        numColumns={numColumns}
        renderItem={_renderItem}
        horizontal={false}
        ItemSeparatorComponent={() => <View style={{ height: gutterSize }} />}
        style={[style, styles.protectedStyle]}
        contentContainerStyle={[contentContainerStyle, styles.protectedStyle]}
      />
    );
  },
);

export default ItemList;
