import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
} from 'react-native';
import { useNavigation, CompositeNavigationProp } from '@react-navigation/native';
import { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './searchScreen.styles';
import { SearchBar, ProviderCard } from '@components';
import { useAppTheme } from '@theme';
import { searchProvidersApi } from '../../../api/deliveryApi';
import { Provider } from '../../../interfaces';
import { AppStackParamList } from '../../../navigation/appStack';
import { MainTabParamList } from '../../../navigation/mainTabNavigator';

type NavProp = CompositeNavigationProp<
  BottomTabNavigationProp<MainTabParamList, 'SearchScreen'>,
  StackNavigationProp<AppStackParamList>
>;

export const SearchScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<NavProp>();

  const [query, setQuery] = useState('');
  const [results, setResults] = useState<Provider[]>([]);

  useEffect(() => {
    if (query.trim().length > 0) {
      searchProvidersApi(query).then(setResults);
    } else {
      setResults([]);
    }
  }, [query]);

  return (
    <View style={styles.container}>
      <SearchBar
        value={query}
        onChangeText={setQuery}
        placeholder="Search providers or items..."
      />
      <FlatList
        data={results}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <ProviderCard
            imageUrl={item.imageUrl}
            name={item.name}
            rating={item.rating}
            deliveryTime={item.deliveryTime}
            tag={item.tag}
            discountText={item.discountText}
            onPress={() =>
              navigation.navigate('ProviderDetailsScreen', {
                providerId: item.id,
                providerName: item.name,
              })
            }
          />
        )}
        ListEmptyComponent={
          query.trim().length > 0 ? (
            <View style={styles.empty}>
              <Text style={styles.emptyText}>No results found</Text>
            </View>
          ) : (
            <View style={styles.empty}>
              <Text style={styles.emptyIcon}>🔍</Text>
              <Text style={styles.emptyText}>Search for food, groceries, medicines...</Text>
            </View>
          )
        }
        contentContainerStyle={styles.list}
      />
    </View>
  );
};
