import React, { useState, useEffect } from 'react';
import { View, FlatList, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { SearchBar } from '../../components/SearchBar';
import { MedicineCard } from '../../components/MedicineCard';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useDebounce } from '../../hooks/useDebounce';
import { searchMedicines } from '../../services/medicines';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { Medicine } from '../../types';
import { config } from '../../constants/config';

export default function HomeScreen() {
  const router = useRouter();
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<Medicine[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const debouncedQuery = useDebounce(query, config.SEARCH_DEBOUNCE_MS);

  useEffect(() => {
    if (debouncedQuery.length < 2) {
      setResults([]);
      return;
    }

    const fetchResults = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const data = await searchMedicines(debouncedQuery);
        setResults(data);
      } catch (err) {
        setError('Error al buscar medicamentos');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchResults();
  }, [debouncedQuery]);

  const handleSearch = (searchQuery: string) => {
    setQuery(searchQuery);
  };

  return (
    <View style={styles.container}>
      <View style={styles.searchContainer}>
        <SearchBar
          onSearch={handleSearch}
          value={query}
          onChangeText={setQuery}
        />
        <TouchableOpacity 
          style={styles.scannerButton}
          onPress={() => router.push('/scanner')}
        >
          <Ionicons name="scan" size={24} color={colors.primary} />
        </TouchableOpacity>
      </View>
      
      {isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
      
      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}
      
      {!isLoading && !error && results.length === 0 && query.length >= 2 && (
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>No se encontraron medicamentos</Text>
        </View>
      )}
      
      <FlatList
        data={results}
        keyExtractor={(item) => item.nregistro}
        renderItem={({ item }) => <MedicineCard medicine={item} />}
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  scannerButton: {
    marginRight: spacing.md,
    padding: spacing.sm,
    backgroundColor: colors.card,
    borderRadius: borderRadius.md,
  },
  list: {
    paddingBottom: spacing.xl,
  },
  errorContainer: {
    padding: spacing.md,
    marginHorizontal: spacing.md,
    backgroundColor: '#F8D7DA',
    borderRadius: 8,
  },
  errorText: {
    color: '#721C24',
    textAlign: 'center',
  },
  emptyContainer: {
    padding: spacing.xl,
    alignItems: 'center',
  },
  emptyText: {
    color: colors.textSecondary,
    fontSize: 16,
  },
});
