import { useState, useEffect, useRef } from "react";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { SearchResults } from "@/lib/types";
import { Card, CardContent } from "@/components/ui/card";
import { useDebounce } from "@/hooks/use-mobile";
import { Link, useLocation } from "wouter";

interface SearchBarProps {
  placeholder?: string;
  className?: string;
  onSearch?: (query: string) => void;
  fullWidth?: boolean;
}

export function SearchBar({ 
  placeholder = "Search by title, author, or keyword", 
  className,
  onSearch,
  fullWidth = false
}: SearchBarProps) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchResults | null>(null);
  const [isSearching, setIsSearching] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const debouncedQuery = useDebounce(query, 300);
  const searchRef = useRef<HTMLDivElement>(null);
  const [location, navigate] = useLocation();

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setIsFocused(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

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

    const fetchResults = async () => {
      setIsSearching(true);
      try {
        const response = await fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`);
        if (response.ok) {
          const data = await response.json();
          setResults(data);
        }
      } catch (error) {
        console.error("Search error:", error);
      } finally {
        setIsSearching(false);
      }
    };

    fetchResults();
  }, [debouncedQuery]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (query.trim()) {
      onSearch?.(query.trim());
      navigate(`/explore?q=${encodeURIComponent(query.trim())}`);
      setIsFocused(false);
    }
  };

  return (
    <div className={`relative ${className}`} ref={searchRef}>
      <form onSubmit={handleSubmit} className={`${fullWidth ? 'w-full' : 'max-w-md'}`}>
        <div className="relative">
          <Input
            type="text"
            placeholder={placeholder}
            className="pl-10 pr-4 py-2 rounded-lg bg-background dark:bg-background border border-input dark:border-input focus:outline-none focus:ring-2 focus:ring-ring"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => setIsFocused(true)}
          />
          <Search className="h-5 w-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground dark:text-muted-foreground" />
          {query && (
            <Button
              type="submit"
              size="sm"
              className="absolute right-2 top-1/2 transform -translate-y-1/2 h-7 text-xs"
            >
              Search
            </Button>
          )}
        </div>
      </form>

      {isFocused && results && (
        <Card className="absolute z-50 w-full mt-1 shadow-lg">
          <CardContent className="p-2">
            {results.authors.length > 0 && (
              <div className="mb-4">
                <h3 className="text-sm font-medium mb-2 text-muted-foreground">Authors</h3>
                <ul className="space-y-1">
                  {results.authors.map((author) => (
                    <li key={author.id}>
                      <Link
                        href={`/authors/${author.slug}`}
                        className="block p-2 hover:bg-primary/5 dark:hover:bg-primary/10 rounded"
                        onClick={() => setIsFocused(false)}
                      >
                        <span className="font-medium">{author.name}</span>
                        {author.country && (
                          <span className="text-xs text-muted-foreground ml-2">
                            {author.country}
                          </span>
                        )}
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {results.works.length > 0 && (
              <div>
                <h3 className="text-sm font-medium mb-2 text-muted-foreground">Works</h3>
                <ul className="space-y-1">
                  {results.works.map((work) => (
                    <li key={work.id}>
                      <Link
                        href={`/works/${work.slug}`}
                        className="block p-2 hover:bg-primary/5 dark:hover:bg-primary/10 rounded"
                        onClick={() => setIsFocused(false)}
                      >
                        <span className="font-medium">{work.title}</span>
                        <span className="text-xs text-muted-foreground ml-2">
                          {work.language}, {work.year || "Unknown"}
                        </span>
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {results.authors.length === 0 && results.works.length === 0 && (
              <p className="py-2 text-muted-foreground text-sm text-center">
                No results found for "{query}"
              </p>
            )}

            <div className="mt-2 pt-2 border-t border-border text-center">
              <Button
                variant="link"
                size="sm"
                className="text-xs text-accent"
                onClick={handleSubmit}
              >
                View all results
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
