import React, { useState } from "react";
import {
    View,
    TextInput,
    TouchableOpacity,
    useColorScheme,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";

interface SearchBarProps {
    placeholder?: string;
    onSearch?: (text: string) => void;
}

//TODO make cirilic==latinic when searching
export default function SearchBar({
    placeholder = "Search…",
    onSearch,
}: SearchBarProps) {
    const [query, setQuery] = useState("");
    const scheme = useColorScheme();
    const dark = scheme === "dark";

    const handleChange = (text: string) => {
        setQuery(text);
        onSearch?.(text);
    };

    return (
        <View
            className={`
        flex-row items-center mx-4 my-3 px-4 rounded-2xl h-11
        ${dark
                    ? "bg-obsidian-100 border border-border-dark"
                    : "bg-parchment-100 border border-border-light"
                }
      `}
        >
            <Ionicons
                name="search"
                size={16}
                color={dark ? "#706D67" : "#8A8278"}
                style={{ marginRight: 8 }}
            />
            <TextInput
                className={`flex-1 text-sm font-sans ${dark ? "text-ink-dark" : "text-ink-light"
                    }`}
                placeholderTextColor={dark ? "#706D67" : "#8A8278"}
                placeholder={placeholder}
                value={query}
                onChangeText={handleChange}
                returnKeyType="search"
                clearButtonMode="while-editing"
            />
            {query.length > 0 && (
                <TouchableOpacity onPress={() => handleChange("")} hitSlop={8}>
                    <Ionicons
                        name="close-circle"
                        size={16}
                        color={dark ? "#706D67" : "#8A8278"}
                    />
                </TouchableOpacity>
            )}
        </View>
    );
}
