import React from 'react';
import type { SectionListRenderItemInfo } from 'react-native';
import type { BaseOptionListProps } from '../BaseOptionList';
import BaseOptionList from '../BaseOptionList';
import Option from './Option';
import type { MultiSelectProps } from '.';
import type { SelectOptionType, SectionType } from '../types';
import { isOptionSelected } from './utils';
import { deepCompareValue } from '../../../utils/helpers';

type OptionListProps<V, T extends SelectOptionType<V>> = Pick<
  MultiSelectProps<V, T>,
  | 'keyExtractor'
  | 'loading'
  | 'onEndReached'
  | 'onQueryChange'
  | 'value'
  | 'renderOption'
> & {
  onPress: (value: V[]) => void;
} & BaseOptionListProps<V, T>;

const OptionList = <V, T extends SelectOptionType<V>>({
  keyExtractor,
  loading,
  onEndReached,
  onPress,
  onQueryChange,
  sections,
  renderOption,
  value,
  sectionListRef,
  ...rest
}: OptionListProps<V, T>) => {
  const renderItem = (info: SectionListRenderItemInfo<T, SectionType>) => {
    const { item } = info;
    const selected = isOptionSelected(value, item);
    const onItemPress = () => {
      if (isOptionSelected(value, item)) {
        onPress(value.filter((val) => !deepCompareValue(val, item.value)));
      } else {
        onPress([...value, item.value]);
      }
    };

    return renderOption ? (
      renderOption({ ...info, selected, onPress: onItemPress })
    ) : (
      <Option
        selected={selected}
        text={item.text}
        disabled={item.disabled}
        onPress={onItemPress}
        highlighted={item.highlighted}
      />
    );
  };

  return (
    <BaseOptionList
      keyExtractor={keyExtractor}
      loading={loading}
      onEndReached={onEndReached}
      onQueryChange={onQueryChange}
      sections={sections}
      renderItem={renderItem}
      sectionListRef={sectionListRef}
      {...rest}
    />
  );
};

export default OptionList;
