import React, { FC, useEffect, useState } from 'react';
import { Text, TouchableOpacity, View, Image, StyleSheet } from 'react-native';
import { NavigationProp, useFocusEffect } from '@react-navigation/native';
import { storage, StoreType } from 'src/storage';
import { PageWrapper, Header, Input, AvatarWithInitials, WarningModal } from 'src/components';
import { usePostGetGroupMembersQuery, usePostGetGroupSettingsQuery } from '@api/chat';
import { Colors } from 'src/theme';
import { API_HOST } from 'src/constants';
import { getFontSize } from 'src/utils';
import { SheetManager } from 'react-native-actions-sheet';
import UserOptionsModal from '../Components/UserOptionsModal';
import { chatStyles } from '../Components/styles';
import { FlashList } from '@shopify/flash-list';

import SearchIcon from 'assets/icons/search.svg';
import DotsIcon from 'assets/icons/messages/dots-vertical.svg';

type Props = {
  navigation: NavigationProp<any>;
  route: any;
};

const MembersListScreen: FC<Props> = ({ navigation, route }) => {
  const token = storage.get('token', StoreType.STRING) as string;
  const currentUserId = storage.get('uid', StoreType.STRING) as string;
  const { groupToken, canChangeAdmin } = route.params;

  const [modalState, setModalState] = useState({
    isWarningVisible: false,
    title: '',
    buttonTitle: '',
    message: '',
    action: () => {}
  });
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const { data, refetch } = usePostGetGroupSettingsQuery(token, groupToken, true);
  const { data: members, refetch: refetchMembers } = usePostGetGroupMembersQuery(
    token,
    groupToken,
    true
  );

  useFocusEffect(() => {
    navigation.getParent()?.setOptions({
      tabBarStyle: {
        display: 'none'
      }
    });
  });

  useEffect(() => {
    if (members && members.settings) {
      setFilteredData(members.settings);
    }
  }, [members]);

  const handleSearch = (text: string) => {
    if (text && members) {
      const searchData =
        members?.settings?.filter((item: any) => {
          const itemData = item.name ? item.name.toLowerCase() : ''.toLowerCase();
          const textData = text.toLowerCase();
          return itemData.indexOf(textData) > -1;
        }) ?? [];
      setFilteredData(searchData);
      setSearchQuery(text);
    } else {
      setFilteredData(members?.settings ?? []);
      setSearchQuery(text);
    }
  };

  const renderItem = ({ item }: { item: any }) => (
    <View style={styles.userItem}>
      {item.avatar ? (
        <Image source={{ uri: API_HOST + item.avatar }} style={chatStyles.avatar} />
      ) : (
        <AvatarWithInitials
          text={item.name?.split(' ')[0][0] + item.name?.split(' ')[1][0]}
          flag={API_HOST + item?.flag1}
          size={36}
          fontSize={12}
          borderColor={Colors.LIGHT_GRAY}
          borderWidth={1}
        />
      )}

      <View style={chatStyles.textContainer}>
        <Text style={chatStyles.name}>{item.name}</Text>
      </View>
      {item.admin === 1 && (
        <Text
          style={{
            fontSize: getFontSize(10),
            fontWeight: '600',
            color: Colors.LIGHT_GRAY
          }}
        >
          Admin
        </Text>
      )}
      {item.uid !== +currentUserId && (
        <TouchableOpacity
          style={{ padding: 6 }}
          onPress={() =>
            SheetManager.show('user-options-modal', {
              payload: {
                admin: item.admin,
                uid: item.uid,
                name: item.name,
                canChangeAdmin,
                token,
                groupToken,
                refetch,
                refetchMembers,
                setIsWarningVisible: setModalState
              } as any
            })
          }
        >
          <DotsIcon />
        </TouchableOpacity>
      )}
    </View>
  );

  return (
    <PageWrapper>
      <Header label="Nomads" />
      <View style={styles.container}>
        <Input
          inputMode={'search'}
          placeholder={'Search nomads'}
          onChange={handleSearch}
          value={searchQuery}
          icon={<SearchIcon fill={'#C8C8C8'} width={14} height={14} />}
        />

        <FlashList
          viewabilityConfig={{
            waitForInteraction: true,
            itemVisiblePercentThreshold: 50,
            minimumViewTime: 1000
          }}
          data={filteredData || []}
          renderItem={renderItem}
          keyExtractor={(item) => item.uid.toString()}
          estimatedItemSize={100}
          extraData={filteredData}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: 16 }}
        />
      </View>

      <WarningModal
        type={'delete'}
        isVisible={modalState.isWarningVisible}
        buttonTitle={modalState.buttonTitle}
        message={modalState.message}
        action={modalState.action}
        onClose={() => setModalState({ ...modalState, isWarningVisible: false })}
        title={modalState.title}
      />
      <UserOptionsModal />
    </PageWrapper>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    gap: 16,
    flex: 1
  },
  avatar: {
    width: 30,
    height: 30,
    borderRadius: 15,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY
  },
  header: {
    paddingTop: 16,
    paddingHorizontal: 6,
    width: 68
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: Colors.FILL_LIGHT,
    gap: 8,
    borderRadius: 8,
    marginBottom: 6
  }
});

export default MembersListScreen;
