import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  Platform
} from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { FlashList } from '@shopify/flash-list';
import { storage, StoreType } from 'src/storage';
import { 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';

const SearchModal = () => {
  const navigation = useNavigation();
  const token = storage.get('token', StoreType.STRING) as string;
  const [searchQuery, setSearchQuery] = useState('');
  const { data: searchResult, isFetching } = usePostSearchUsers(
    token,
    searchQuery,
    searchQuery.length > 1
  );

  useEffect(() => {}, [searchResult]);

  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
              }
            ] 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={30}
          fontSize={12}
        />
      )}

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

  return (
    <ActionSheet
      id="search-modal"
      gestureEnabled={Platform.OS === 'ios'}
      onClose={() => setSearchQuery('')}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      indicatorStyle={{ backgroundColor: 'transparent' }}
    >
      <View style={styles.container}>
        <Input
          inputMode={'search'}
          placeholder={'Search nomads'}
          onChange={(text) => {
            setSearchQuery(text);
          }}
          value={searchQuery}
          icon={<SearchIcon fill={'#C8C8C8'} width={14} height={14} />}
        />

        {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}
            />
          </View>
        )}
      </View>
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    height: '80%',
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    paddingHorizontal: 16,
    paddingVertical: 12
  },
  container: {
    backgroundColor: 'white',
    gap: 12,
    height: '100%'
  },
  searchInput: {
    height: 40,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 10,
    marginBottom: 10
  },
  itemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    gap: 8
  },
  avatar: {
    width: 30,
    height: 30,
    borderRadius: 15,
    borderWidth: 1,
    borderColor: Colors.FILL_LIGHT
  },
  textContainer: {
    flex: 1
  },
  name: {
    fontSize: getFontSize(14),
    color: Colors.DARK_BLUE,
    fontFamily: 'montserrat-700'
  }
});

export default SearchModal;
