import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { FormEvent, useRef, useEffect } from "react";

interface SearchInputProps {
  query: string;
  onQueryChange: (q: string) => void;
  onSearch: (q: string) => void;
  compact?: boolean;
  autoFocus?: boolean;
}

export function SearchInput({ query, onQueryChange, onSearch, compact, autoFocus }: SearchInputProps) {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (autoFocus) inputRef.current?.focus();
  }, [autoFocus]);

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    onSearch(query);
  };

  return (
    <form onSubmit={handleSubmit} className={`flex items-center gap-2 w-full ${compact ? "max-w-xl" : "max-w-2xl"}`}>
      <div className="relative flex-1">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={compact ? 16 : 20} />
        <Input
          ref={inputRef}
          value={query}
          onChange={(e) => onQueryChange(e.target.value)}
          placeholder="Search the web privately..."
          className={`pl-10 pr-4 border-input bg-background focus-visible:ring-ring ${compact ? "h-9 text-sm" : "h-12 text-base"}`}
        />
      </div>
      <Button type="submit" size={compact ? "sm" : "default"} className="bg-primary text-primary-foreground hover:bg-primary/90 shrink-0">
        Search
      </Button>
    </form>
  );
}
