import React, {useCallback} from 'react';
import {FlatList, ListRenderItem, Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Check, ListEmpty, ListFooter, ListRow} from '@components/_HuGo';
import {Segmentation} from '@interfaces/user';

import {styles} from './styles';
import CollapsibleGroup from '../CollapsibleGroup';

export interface SegmentationGroupsProps {
  disabled?: boolean;
  onToggleItem: (item: number) => void;
  selectedSegmentationItemIds: number[];
  segmentationItems: Segmentation[];
  isLoading: boolean;
}

function SegmentationGroups({
  onToggleItem: onToggleItemProp,
  selectedSegmentationItemIds,
  segmentationItems,
  isLoading,
}: SegmentationGroupsProps) {
  const {t} = useTranslation();

  const onToggleItem = useCallback(
    (item: number) => () => {
      onToggleItemProp(item);
    },
    [onToggleItemProp],
  );

  const renderItem: ListRenderItem<Segmentation> = useCallback(
    ({item: group}) => {
      const groupItemsSelected = group.items?.filter(item =>
        selectedSegmentationItemIds.some(i => i === item.id),
      )?.length;
      const title = group.name ? `${group.name}` : '';
      return (
        <CollapsibleGroup
          title={title}
          description={`${groupItemsSelected}/${group.items?.length}`}>
          {group.items?.map(item => (
            <Pressable
              style={styles.itemRow}
              onPress={onToggleItem(item.id)}
              key={item.id}>
              <Check
                onPress={onToggleItem(item.id)}
                checked={selectedSegmentationItemIds.some(i => i === item.id)}
              />
              <ListRow.Title title={item.name} />
            </Pressable>
          ))}
        </CollapsibleGroup>
      );
    },
    [onToggleItem, selectedSegmentationItemIds],
  );

  return (
    <FlatList
      data={segmentationItems}
      showsVerticalScrollIndicator={false}
      ListFooterComponent={
        <ListFooter paginationType="infiniteScroll" isVisible={isLoading} />
      }
      ListEmptyComponent={
        isLoading ? null : (
          <ListEmpty title={t('general.empty')} style={styles.emptyList} />
        )
      }
      renderItem={renderItem}
      keyExtractor={item => `${item.id}`}
    />
  );
}

export default SegmentationGroups;
