import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Image, ActivityIndicator } from 'react-native';
import { Colors } from 'src/theme';
import { Input } from 'src/components';
import { storage, StoreType } from 'src/storage';
import { usePostSearchUsers } from '@api/chat';
import { API_HOST } from 'src/constants';
import { AvatarWithInitials } from 'src/components';

import SearchIcon from 'assets/icons/search.svg';
import CheckSvg from 'assets/icons/travels-screens/circle-check.svg';
import { FlashList } from '@shopify/flash-list';
import { useSheetRouter } from 'react-native-actions-sheet';
import { getFontSize } from 'src/utils';

import CloseIcon from 'assets/icons/close.svg';
import { useGetMyFriendsMutation } from '@api/friends';
import { useGroupChatStore } from 'src/stores/groupChatStore';

const RouteAddUsers = () => {
  const router = useSheetRouter('search-modal');
  const token = storage.get('token', StoreType.STRING) as string;

  const { selectedUsers, addUser, removeUser, clearStore } = useGroupChatStore();

  const [searchQuery, setSearchQuery] = useState('');
  const [friends, setFriends] = useState<any[]>([]);
  const [page, setPage] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [maxPages, setMaxPages] = useState(1);

  const { mutateAsync: getMyFriends } = useGetMyFriendsMutation();

  const { data: searchResult, isFetching } = usePostSearchUsers(
    token,
    searchQuery,
    searchQuery.length > 1
  );

  useEffect(() => {
    getMyFriends(
      {
        token,
        type: 'friends',
        page: 0
      },
      {
        onSuccess: (data) => {
          setFriends(data.friends.users);
          setMaxPages(data.friends.max_pages);
        }
      }
    );
  }, []);

  useEffect(() => {
    const getNextPage = async () => {
      await getMyFriends(
        {
          token,
          type: 'friends',
          page
        },
        {
          onSuccess: (data) => {
            setIsLoadingMore(false);
            setFriends((prevState) => [...prevState, ...data['friends'].users]);
          }
        }
      );
    };
    if (page !== 0) {
      getNextPage();
    }
  }, [page]);

  const handleEndReached = useCallback(() => {
    if (friends && page < maxPages && !isLoadingMore && maxPages > 1) {
      setIsLoadingMore(true);
      setPage((prevPage) => prevPage + 1);
    }
  }, [friends, page]);

  const toggleUserSelection = (user: any) => {
    const isSelected = selectedUsers.some((selected) => selected.user_id === user.user_id);
    if (isSelected) {
      removeUser(user.user_id);
    } else {
      addUser(user);
    }
  };

  const renderUserItem = ({ item }: { item: any }) => {
    const isSelected = selectedUsers.some((selected) => selected.user_id === item.user_id);
    return (
      <TouchableOpacity style={styles.userItem} onPress={() => toggleUserSelection(item)}>
        {item.avatar ? (
          <Image source={{ uri: API_HOST + item.avatar }} style={styles.avatar} />
        ) : (
          <AvatarWithInitials
            text={`${item.first_name[0] ?? ''}${item.last_name[0] ?? ''}`}
            flag={API_HOST + item.flag1}
            size={36}
            fontSize={16}
            borderColor={Colors.LIGHT_GRAY}
            borderWidth={1}
          />
        )}
        <View style={styles.userDetails}>
          <Text style={styles.userName}>
            {item.first_name} {item.last_name}
          </Text>
        </View>
        <View style={styles.unselectedCircle}>
          {isSelected && <CheckSvg fill={Colors.DARK_BLUE} height={20} width={20} />}
        </View>
      </TouchableOpacity>
    );
  };

  const renderSelectedUser = ({ item }: { item: any }) => (
    <View style={styles.selectedUserContainer}>
      <TouchableOpacity onPress={() => removeUser(item.user_id)} style={styles.removeIcon}>
        <CloseIcon width={10} height={10} fill={Colors.WHITE} />
      </TouchableOpacity>
      {item.avatar ? (
        <Image source={{ uri: API_HOST + item.avatar }} style={styles.selectedAvatar} />
      ) : (
        <AvatarWithInitials
          text={`${item.first_name[0] ?? ''}${item.last_name[0] ?? ''}`}
          flag={API_HOST + item.flag1}
          size={60}
          fontSize={21}
          borderColor={Colors.LIGHT_GRAY}
          borderWidth={1}
        />
      )}
    </View>
  );

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => {
            clearStore();
            router?.goBack();
          }}
          style={{
            paddingTop: 16,
            paddingBottom: 6,
            paddingHorizontal: 6
          }}
        >
          <Text style={styles.headerText}>Cancel</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => router?.navigate('route-add-group', { users: selectedUsers })}
          style={{
            paddingTop: 16,
            paddingBottom: 6,
            paddingHorizontal: 6
          }}
        >
          <Text style={styles.headerText}>Next</Text>
        </TouchableOpacity>
      </View>

      <Input
        inputMode={'search'}
        placeholder={'Search nomads'}
        onChange={(text) => {
          setSearchQuery(text);
        }}
        value={searchQuery}
        icon={<SearchIcon fill={'#C8C8C8'} width={14} height={14} />}
      />

      {selectedUsers.length > 0 && (
        <View style={styles.usersRow}>
          <FlashList
            horizontal
            data={selectedUsers}
            renderItem={renderSelectedUser}
            keyExtractor={(item) => item.user_id.toString()}
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.selectedUsersList}
            estimatedItemSize={50}
          />
        </View>
      )}

      {isFetching ? (
        <ActivityIndicator size="large" color={Colors.DARK_BLUE} />
      ) : searchQuery ? (
        <FlashList
          viewabilityConfig={{
            waitForInteraction: true,
            itemVisiblePercentThreshold: 50,
            minimumViewTime: 1000
          }}
          data={searchResult?.data || []}
          renderItem={renderUserItem}
          keyExtractor={(item) => item.user_id.toString()}
          estimatedItemSize={100}
          extraData={selectedUsers}
          showsVerticalScrollIndicator={false}
          refreshing={isFetching}
          contentContainerStyle={{ paddingBottom: 16 }}
        />
      ) : (
        <FlashList
          viewabilityConfig={{
            waitForInteraction: true,
            itemVisiblePercentThreshold: 50,
            minimumViewTime: 1000
          }}
          data={friends || []}
          renderItem={renderUserItem}
          keyExtractor={(item) => item.user_id.toString()}
          estimatedItemSize={100}
          extraData={selectedUsers}
          showsVerticalScrollIndicator={false}
          refreshing={isFetching}
          onEndReached={handleEndReached}
          onEndReachedThreshold={0.2}
          contentContainerStyle={{ paddingBottom: 16 }}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    gap: 16,
    height: '100%',
    backgroundColor: Colors.WHITE
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  headerText: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontWeight: '700'
  },
  photoContainer: {
    alignItems: 'center',
    gap: 8
  },
  groupPhoto: {
    width: 80,
    height: 80,
    borderRadius: 40
  },
  photoText: {
    color: Colors.DARK_BLUE,
    fontSize: 14,
    fontFamily: 'montserrat-600'
  },
  input: {
    marginBottom: 12
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: Colors.FILL_LIGHT,
    gap: 8,
    borderRadius: 8,
    marginBottom: 6
  },
  avatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY
  },
  userDetails: {
    flex: 1
  },
  userName: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700'
  },
  userSubtitle: {
    color: Colors.DARK_BLUE,
    fontSize: 14,
    fontFamily: 'montserrat-500'
  },
  userNM: {
    color: Colors.DARK_BLUE,
    fontSize: 14,
    fontFamily: 'montserrat-700',
    marginRight: 12
  },
  unselectedCircle: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY,
    justifyContent: 'center',
    alignItems: 'center'
  },
  usersRow: {
    backgroundColor: Colors.FILL_LIGHT,
    borderRadius: 8
  },
  selectedUsersList: {
    paddingHorizontal: 12,
    paddingVertical: 10
  },
  selectedUserContainer: {
    position: 'relative',
    marginRight: 12
  },
  selectedAvatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY
  },
  removeIcon: {
    position: 'absolute',
    top: -4,
    right: -4,
    width: 22,
    height: 22,
    borderRadius: 11,
    borderWidth: 1,
    borderColor: Colors.WHITE,
    backgroundColor: Colors.RED,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1
  }
});

export default RouteAddUsers;
