import React, { useState, useCallback, useEffect } from 'react';
import {
  TextInput,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator
} from 'react-native';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { getUser } from '@/components/services/SecureStore';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import debounce from 'lodash.debounce';
import { searchUsers, sendRelationshipRequest } from '@/constants/APIs';
import type { User, RelationshipData } from '@/constants/Types';

const RequestRelationship:
  React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => {
  const scheme = useColorScheme() ?? 'dark';
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<number | null>(null);

  useEffect(() => {
    const fetchCurrentUser = async () => {
      const user = await getUser();
      if (user) {
        setCurrentUserId(user.id);
      }
    };
    fetchCurrentUser();
  }, []);

  const handleSearchUsers = useCallback(debounce(async (term: string) => {
    if (term.length < 3) {
      setSearchResults([]);
      return;
    }
    const user = await getUser() as User;
    setIsLoading(true);
    console.log(user.id, encodeURIComponent(term));
    const users: User[] = await searchUsers(user.id, encodeURIComponent(term)) as User[];
    console.log(users);
    setSearchResults(users);
    setIsLoading(false);
  }, 300), []);

  const handleSearch = async (text: string) => {
    setSearchTerm(text);
    handleSearchUsers(text);
  };

  const handleSendRequest = async (targetUserId: number) => {
    if (!currentUserId) return;
    try {
      const relationshipData: RelationshipData =
        await sendRelationshipRequest(currentUserId, targetUserId) as RelationshipData;
      onRequestSent(relationshipData);
    } catch (error) {
      console.error('Error sending relationship request:', error);
    }
  };

  const renderUserItem = ({ item }: { item: User }) => (
    <TouchableOpacity style={styles.userItem} onPress={() => handleSendRequest(item.id)}>
      <ThemedText>{item.fullName}</ThemedText>
      <ThemedText>{item.email}</ThemedText>
    </TouchableOpacity>
  );

  return (
    <ThemedView style={styles.container}>
      <TextInput
        style={[
          styles.searchInput,
          {color: Colors[scheme].text}
        ]}
        placeholder="Search users..."
        value={searchTerm}
        onChangeText={handleSearch}
      />
      {isLoading ? (
        <ActivityIndicator />
      ) : (
        <FlatList
          data={searchResults}
          renderItem={renderUserItem}
          keyExtractor={(item) => item.id.toString()}
          ListEmptyComponent={<ThemedText>No users found</ThemedText>}
        />
      )}
    </ThemedView>
  );
};
export default RequestRelationship;


const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  searchInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 20,
    paddingHorizontal: 10,
  },
  userItem: {
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: 'gray',
  },
});
