import React, { HTMLAttributes, ReactElement, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap, KeyedItem, PickerState } from '@wix/bex-core';
import { useCollectionReachBottom } from '../useCollectionReachBottom';
import { Box } from '@wix/design-system';
import { InfiniteScrollLoader } from '../InfiniteScrollLoader/InfiniteScrollLoader';
import { PickerListItemProps } from '../PickerListItemProps';
import { TransitionGroup } from 'react-transition-group';
import { useIsScrollTop } from '../../hooks/useIsScrollTop';
import { Fade } from '../Fade';

export interface PickerListContentProps<T, F extends FiltersMap>
  extends HTMLAttributes<HTMLDivElement> {
  state: PickerState<T, F>;
  renderItem: (
    keyedItem: KeyedItem<T>,
    index: number,
  ) => ReactElement<PickerListItemProps>;
  spacing?: 30 | 94;
  multiple?: boolean;
}

function _PickerListContent<T, F extends FiltersMap = FiltersMap>(
  props: PickerListContentProps<T, F>,
) {
  const { state, renderItem, spacing = 30, multiple, ...rest } = props;

  const { collection } = state;
  const {
    result: { keyedItems },
  } = collection;

  const scrollRef = useRef<HTMLDivElement>(null);
  const { targetRef } = useCollectionReachBottom({
    collection,
    containerRef: scrollRef,
  });
  const isScrollTop = useIsScrollTop(scrollRef);

  useEffect(() => {
    state.updateIsScrollTop(isScrollTop);
  }, [isScrollTop]);

  const listItems: ReactElement[] = keyedItems.map((keyedItem, index) => {
    const { type: PickerListItem, props: pickerListItemProps } = renderItem(
      keyedItem,
      index,
    );
    return (
      <PickerListItem
        dataHook="selector-list-selector"
        key={keyedItem.key}
        keyedItem={keyedItem}
        state={state}
        multiple={multiple}
        {...pickerListItemProps}
      />
    );
  });

  return (
    <div
      ref={scrollRef}
      {...rest}
      data-hook="selector-list-content"
      style={{
        height: 'inherit',
        overflow: 'auto',
        ...rest.style,
      }}
    >
      <TransitionGroup>
        {listItems.flatMap((child, index, { length }) => {
          return (
            <Fade key={child.key} timeout={300}>
              <Box direction="vertical" dataHook="picker-list-fade-item">
                {child}
                {index !== length - 1 && (
                  <Box paddingLeft="SP5" paddingRight="SP5">
                    <Box width="100%" height="1px" backgroundColor="D60" />
                  </Box>
                )}
              </Box>
            </Fade>
          );
        })}
      </TransitionGroup>

      <InfiniteScrollLoader
        targetRef={targetRef}
        state={collection}
        size="small"
      />
    </div>
  );
}

export const PickerListContent = observer(_PickerListContent);
