import React, { useEffect, useState } from 'react';
import { View, Text, Image, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
import { FlashList } from '@shopify/flash-list';
import { storage, StoreType } from 'src/storage';
import { usePostCanCreateGroupQuery, usePostSearchUsers } from '@api/chat';
import { API_HOST } from 'src/constants';
import { Colors } from 'src/theme';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { getFontSize } from 'src/utils';
import { AvatarWithInitials, Input } from 'src/components';

import SearchIcon from 'assets/icons/search.svg';
import NomadsIcon from 'assets/icons/bottom-navigation/travellers.svg';
import { SheetManager, useSheetRouter } from 'react-native-actions-sheet';

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

  const { data: canCreateGroup } = usePostCanCreateGroupQuery(token, true);
  const [searchQuery, setSearchQuery] = useState('');

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

  const renderItem = ({ item }: { item: any }) => (
    <TouchableOpacity
      style={styles.itemContainer}
      onPress={() => {
        SheetManager.hide('search-modal').then(() => {
          navigation.navigate(
            ...([
              NAVIGATION_PAGES.CHAT,
              {
                id: item.user_id,
                name: item.first_name + ' ' + item.last_name,
                avatar: item.avatar,
                userType: 'normal'
              }
            ] as never)
          );
        });
      }}
    >
      {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.homebase_flag}
          size={36}
          fontSize={12}
          borderColor={Colors.LIGHT_GRAY}
          borderWidth={1}
        />
      )}

      <View style={styles.textContainer}>
        <Text style={styles.name}>
          {item.first_name} {item.last_name}
        </Text>
      </View>
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.header} onPress={() => router?.goBack()}>
        <Text style={styles.cancelText}>Cancel</Text>
      </TouchableOpacity>

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

      {canCreateGroup && canCreateGroup.authorized === 1 ? (
        <TouchableOpacity
          style={styles.newGroup}
          onPress={() => router?.navigate('route-add-users')}
        >
          <Text style={styles.text}>New group chat</Text>
          <NomadsIcon fill={Colors.DARK_BLUE} width={20} height={16} />
        </TouchableOpacity>
      ) : null}

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

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    gap: 16,
    height: '100%'
  },
  header: {
    paddingTop: 16,
    paddingHorizontal: 6,
    width: 68
  },
  cancelText: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontWeight: '700'
  },
  itemContainer: {
    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
  },
  textContainer: {
    flex: 1
  },
  name: {
    fontSize: getFontSize(14),
    color: Colors.DARK_BLUE,
    fontFamily: 'montserrat-700'
  },
  newGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    backgroundColor: Colors.FILL_LIGHT,
    borderRadius: 8,
    height: 44
  },
  text: {
    fontSize: getFontSize(12),
    color: Colors.DARK_BLUE,
    fontWeight: '700'
  }
});

export default RouteSearch;
