
import React, { Fragment, useEffect, useState } from 'react';
import {
  Dimensions,
  FlatList,
  ImageStyle,
  ListRenderItem,
  StyleSheet,
  Text,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { IStyledProps } from './types';
import { AvatarPresenceBadge } from '../presence';
import Icon from 'react-native-vector-icons/Ionicons';
import { IPeer } from '../../store/peer/types';
import { Divider, IconButton } from 'react-native-paper';


interface IParticipantsProps extends IStyledProps<IParticipantsStyleProps> {
  onParticipantsUpdated: (participantsId: string[]) => void;
  participants: IPeer[];
  renderParticipantContainer?:(participant: IPeer ) => React.ReactNode;
}
interface IParticipantsStyleProps {
  noDataMessageText?: TextStyle;
  noDataContainer?: ViewStyle;
  list?: ViewStyle;
  selected?: ViewStyle;
  presenceIcon?: ImageStyle;
  profilePicContainer?: ViewStyle
}

export const ParticipantsListView: React.FunctionComponent<IParticipantsProps> = ({
  participants,
  style,
  onParticipantsUpdated,
  renderParticipantContainer
}) => {
  const mergedStyle = { ...defaultStyle, ...style };
  const [participantsToSelect, setParticipantsToSelect] = useState<IPeer[]>(participants || []);
  const [refresh, setRefresh] = useState<boolean>(true);
  const [participantsToInvite, setParticipantsToInvite] = useState<string[]>([]);

  useEffect(() => {
    const participantsToSelect = participants.map((item) => {
      item.isSelected = false;
      item.selectedClass = mergedStyle.list;
      return {...item, isSelected: false, selectedClass: mergedStyle.list };
    });
setParticipantsToSelect(participantsToSelect);

    return () => {
      setParticipantsToInvite([]);
      participants?.forEach(participant => {
        participant.isSelected = false
        participant.selectedClass = mergedStyle.list
      });
    }
  }, [participants]);

  const selectParticipant = (participant: IPeer) => {
    setRefresh(!refresh);
    participant.isSelected = !participant.isSelected;
    participant.selectedClass = participant.isSelected
      ? mergedStyle.selected
      : mergedStyle.list;
    const index = participantsToSelect.findIndex(
      (item) => participant.jId === item.jId
    );

    participantsToSelect[index] = participant;
    addParticipantToInvite(participant);
    setParticipantsToSelect(participantsToSelect);
  };
  const ListEmpty = () => {
    return (
      <View style={mergedStyle.noDataContainer}>
        <Text style={mergedStyle.noDataMessageText}>No Participants Found</Text>
      </View>
    );
  };
  const updateParentState = (state: string[]) => {
    onParticipantsUpdated(state);
  };
  const addParticipantToInvite = (participant: IPeer) => {
    if (participant.isSelected) {
      participantsToInvite.push(participant.jId);
    } else {
      participantsToInvite.splice(
        participantsToInvite.indexOf(participant.jId),
      1
      );
    }
    setParticipantsToInvite(participantsToInvite);
    updateParentState(participantsToInvite);
  };

  const renderParticipantView: ListRenderItem<IPeer> = ({ item }: { item: IPeer }) => {
    const backgroundColor = item.selectedClass;
    return(
      <Fragment>
      {renderParticipantContainer ? (
        renderParticipantContainer(item)
      ) : (
        <TouchableOpacity
          onPress={() => selectParticipant(item)}
          style={[{ overflow: 'hidden' }, backgroundColor]}
        >
          <View style={{ flexDirection: 'row', paddingHorizontal: 12, justifyContent: 'space-between', width: '100%' }}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
              <AvatarPresenceBadge peer={item} presence={undefined} />
              <Text style={{ alignSelf: 'center' }}>{item.name}</Text>
            </View>
            {item.isSelected && (
              <IconButton icon="check" size={30} iconColor="#67bf57" />
            )}
          </View>
          <Divider style={{ marginHorizontal: 75, marginVertical: 8, backgroundColor: '#e0e0e0' }} />
        </TouchableOpacity>
      )}
    </Fragment>
    )
  };
    
  const keyExtractor = (participant: IPeer) => {
    return participant.jId;
  };

  return (
    <FlatList
      keyboardShouldPersistTaps="always"
      data={participantsToSelect}
      extraData={refresh}
      renderItem={renderParticipantView}
      ListEmptyComponent={ListEmpty}
      keyExtractor={keyExtractor}
    />
  );
};

const defaultStyle = StyleSheet.create({
  list: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 10,
    backgroundColor: '#FFFFFF',
  },
  selected: {
    backgroundColor: 'rgba(	204, 230, 245, 0.8)',
  },
  noDataContainer: {
    fontSize: 25,
    justifyContent: 'center',
    flex: 1,
    marginTop: 100,
  },
  noDataMessageText: {
    textAlign: 'center',
  },
  presenceIcon: {
    top: 55,
    marginLeft: 42,
  },
  profilePicContainer: {
    width: 60,
    height: 60,
    borderRadius: 30,
  },
  checkIcon: { fontSize: 35, color: '#67bf57', position: 'absolute', right: 10 }
});

