import { useState } from 'react'
import {
  View, Text, TextInput, FlatList,
  TouchableOpacity, ActivityIndicator,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { Search as SearchIcon, X } from 'lucide-react-native'
import { useRouter } from 'expo-router'
import { apiFetch } from '@/lib/api'
import { ENDPOINTS } from '@/lib/config'

interface SearchResult {
  id: string
  title: string
  snippet: string
  notebookName?: string
  score?: number
}

export default function SearchScreen() {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<SearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [searched, setSearched] = useState(false)
  const router = useRouter()

  const handleSearch = async () => {
    if (!query.trim()) return
    setLoading(true)
    setSearched(true)
    try {
      const res = await apiFetch(`${ENDPOINTS.search}?q=${encodeURIComponent(query)}`)
      if (res.ok) {
        const data = await res.json()
        setResults(data.results ?? [])
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <SafeAreaView className="flex-1 bg-paper">
      <View className="px-5 pt-4 pb-2">
        <Text className="text-2xl font-serif italic text-ink mb-4">Recherche</Text>

        <View className="flex-row items-center bg-white border border-border rounded-xl px-3 py-2.5 gap-2">
          <SearchIcon size={16} color="#8A8A82" />
          <TextInput
            value={query}
            onChangeText={setQuery}
            placeholder="Chercher dans vos notes…"
            className="flex-1 text-[15px] text-ink"
            placeholderTextColor="#8A8A82"
            returnKeyType="search"
            onSubmitEditing={handleSearch}
          />
          {query.length > 0 && (
            <TouchableOpacity onPress={() => { setQuery(''); setResults([]); setSearched(false) }}>
              <X size={14} color="#8A8A82" />
            </TouchableOpacity>
          )}
        </View>
      </View>

      {loading ? (
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator color="#A47148" />
        </View>
      ) : (
        <FlatList
          data={results}
          keyExtractor={(item) => item.id}
          contentContainerClassName="px-5 pt-3 pb-8"
          renderItem={({ item }) => (
            <TouchableOpacity
              onPress={() => router.push(`/note/${item.id}`)}
              className="bg-white border border-border rounded-2xl p-4 mb-2.5 active:opacity-70"
            >
              <Text className="text-[15px] font-semibold text-ink" numberOfLines={1}>
                {item.title || 'Sans titre'}
              </Text>
              {item.snippet && (
                <Text className="text-[12px] text-concrete mt-1" numberOfLines={2}>
                  {item.snippet}
                </Text>
              )}
              {item.notebookName && (
                <Text className="text-[11px] text-concrete/60 mt-1">{item.notebookName}</Text>
              )}
            </TouchableOpacity>
          )}
          ListEmptyComponent={
            searched ? (
              <Text className="text-concrete text-center mt-12">Aucun résultat pour "{query}"</Text>
            ) : (
              <Text className="text-concrete text-center mt-12 text-[13px]">
                Tapez votre recherche puis appuyez sur Entrée
              </Text>
            )
          }
        />
      )}
    </SafeAreaView>
  )
}
