import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {FlatList, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useNavigation} from '@react-navigation/native';
import {Dialog, InputSearch} from '@components';
import {useDebounce} from '@hooks/useDebounce';
import {Membership} from '@modules/chats/interfaces';
import {getUsersFromChannelService} from '@modules/chats/db';
import {SPACING} from '@shared/theme';
import {Screens} from '@shared/constants';

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

interface Props {
  channel: string;
  isUserAdmin: boolean;
  isVisible: boolean;
  totalMembers: number;
  onClose: () => void;
  onMemberActionsPress: (membership: Membership) => void;
}

const keyExtractor = (item: Membership) => `${item.user.id}`;

function DialogAllMembers({
  channel,
  isUserAdmin,
  isVisible,
  onClose,
  totalMembers,
  onMemberActionsPress,
}: Props) {
  const {t} = useTranslation();
  const {bottom} = useSafeAreaInsets();
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 500);
  const [groupMembers, setGroupMembers] = useState<Membership[]>([]);
  const page = useRef(1);
  const navigation = useNavigation();
  const getFirstMemberships = useCallback(async () => {
    page.current = 1;
    const currentUsersMemberships = await getUsersFromChannelService({
      channel,
      page: page.current,
      search: debouncedSearch,
    });
    setGroupMembers(currentUsersMemberships);
  }, [channel, debouncedSearch]);

  const getMoreMembers = useCallback(async () => {
    page.current += 1;
    const currentUsersMemberships = await getUsersFromChannelService({
      channel,
      page: page.current,
      search: debouncedSearch,
    });
    setGroupMembers(prev => [...prev, ...currentUsersMemberships]);
  }, [channel, debouncedSearch]);

  const onRedirectToProfile = useCallback(
    (userId: number) => {
      onClose();
      navigation.navigate(Screens.PROFILE, {userId});
    },
    [onClose, navigation],
  );

  const renderUsers = useCallback(
    ({item}: {item: Membership}) => {
      return (
        <MemberItem
          membership={item}
          isUserAdmin={isUserAdmin}
          currentHasYouReference
          onMemberActionsPress={onMemberActionsPress}
          onRedirectToProfile={onRedirectToProfile}
        />
      );
    },
    [isUserAdmin, onMemberActionsPress, onRedirectToProfile],
  );

  const onChangeSearch = useCallback((text: string) => {
    setSearch(text);
  }, []);

  useEffect(() => {
    if (isVisible) {
      getFirstMemberships();
    }
  }, [channel, getFirstMemberships, isVisible]);

  const memorizedStyles = useMemo(
    () => ({
      contentContainer: {
        paddingBottom: bottom + SPACING.x2,
      },
    }),
    [bottom],
  );

  return (
    <Dialog
      isVisible={isVisible}
      onClose={onClose}
      title={t('chat.groups.all_members')}
      subtitle={t('general.collaborator_count_other', {count: totalMembers})}
      wrapperType="none"
      contentStyle={styles.dialog}
      enableContentPanningGesture={false}
      fullScreen>
      <View style={styles.container}>
        <InputSearch
          value={search}
          placeholder={t('general.search')}
          onChangeText={onChangeSearch}
          variant="custom"
        />
        <FlatList
          data={groupMembers}
          keyExtractor={keyExtractor}
          renderItem={renderUsers}
          showsVerticalScrollIndicator={false}
          onEndReached={getMoreMembers}
          contentContainerStyle={memorizedStyles.contentContainer}
        />
      </View>
    </Dialog>
  );
}

export default DialogAllMembers;
