import { useTheme } from '@emotion/react';
import React, { useState } from 'react';
import type { SectionList, SectionListProps } from 'react-native';
import { Dimensions, View } from 'react-native';
import SectionHeading from '../SectionHeading';
import Spinner from '../Spinner';
import { OptionSpacer, SectionSpacer, StyledSectionList } from './StyledSelect';
import type { SelectOptionType, SelectProps, SectionType } from './types';

export type BaseOptionListProps<V, T extends SelectOptionType<V>> = Pick<
  SelectProps<V, T>,
  'keyExtractor' | 'loading' | 'onEndReached' | 'onQueryChange'
> & {
  sectionListRef?: React.RefObject<SectionList<T, SectionType> | null>;
} & SectionListProps<T, SectionType>;

const BaseOptionList = <V, T extends SelectOptionType<V>>({
  keyExtractor,
  loading,
  onEndReached,
  onQueryChange,
  sections,
  renderItem,
  sectionListRef,
  ...rest
}: BaseOptionListProps<V, T>) => {
  const theme = useTheme();

  const [onEndReachedCalled, setOnEndReachedCalled] = useState(false);

  return (
    <StyledSectionList<T, SectionType>
      ref={sectionListRef}
      style={{
        ...(onQueryChange ? { height: Dimensions.get('screen').height } : {}),
      }}
      sections={sections}
      keyExtractor={keyExtractor}
      onEndReachedThreshold={0.1}
      onEndReached={() => setOnEndReachedCalled(true)}
      onMomentumScrollBegin={() => {
        if (onEndReached && onEndReachedCalled && !loading) onEndReached();
        setOnEndReachedCalled(false);
      }}
      ListFooterComponent={
        loading ? (
          <View
            style={{
              display: 'flex',
              alignItems: 'center',
              height: theme.space.xxxxlarge,
            }}
          >
            <Spinner testID="select-loading-spinner" />
          </View>
        ) : null
      }
      renderSectionHeader={({ section: { category } }) =>
        category !== '' ? (
          <SectionHeading
            text={category}
            style={{
              marginBottom: 0,
            }}
          />
        ) : null
      }
      renderItem={renderItem}
      ItemSeparatorComponent={OptionSpacer}
      SectionSeparatorComponent={SectionSpacer}
      {...rest}
    />
  );
};

export default BaseOptionList;
