import React, { useState, useRef } from 'react';
import { Search, X } from 'lucide-react';
import { searchTopics } from '@/lib/services/search';

interface SearchAnswer {
  title: string;
  url: string;
  excerpt: string;
}

interface SearchInputProps {
  initialQuery?: string;
  showDropdown?: boolean;
}

export default function SearchInput({ initialQuery = '', showDropdown = true }: SearchInputProps) {
  const [query, setQuery] = useState(initialQuery);
  const [answers, setAnswers] = useState<SearchAnswer[]>([]);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setQuery(value);

    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }

    if (!showDropdown || value.trim().length < 2) {
      setAnswers([]);
      return;
    }

    debounceRef.current = setTimeout(async () => {
      try {
        const response = await searchTopics(value.trim(), { useWebSearch: false });
        setAnswers(response.results.slice(0, 5));
      } catch {
        setAnswers([]);
      }
    }, 300);
  };

  const handleClear = () => {
    setQuery('');
    setAnswers([]);
    if (!showDropdown) {
      window.location.href = '/search';
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (query.trim()) {
      window.location.href = `/search?q=${encodeURIComponent(query.trim())}`;
    }
  };

  return (
    <div className="w-full max-w-xl mx-auto">
      <form onSubmit={handleSubmit}>
        <div className="relative">
          <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-stone-400" />
          <input
            type="search"
            name="q"
            value={query}
            onChange={handleInputChange}
            placeholder="Search"
            className="w-full pl-12 pr-12 py-3 text-base bg-stone-100 dark:bg-slate-700/50 rounded-xl focus:outline-none [&::-webkit-search-cancel-button]:hidden"
          />
          {query && (
            <button
              type="button"
              onClick={handleClear}
              className="absolute right-3 top-1/2 transform -translate-y-1/2"
            >
              <X className="h-4 w-4 text-stone-400 hover:text-stone-600" />
            </button>
          )}
        </div>
      </form>

      {showDropdown && answers.length > 0 && (
        <div className="mt-4 divide-y divide-border rounded-xl bg-background">
          {answers.map((answer, i) => (
            <a key={i} href={answer.url} className="block px-4 py-4 hover:bg-muted/30">
              <h3 className="font-medium text-foreground mb-1">
                {answer.title.replace(/_/g, ' ')}
              </h3>
              <p
                className="text-sm text-muted-foreground"
                dangerouslySetInnerHTML={{
                  __html: answer.excerpt.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>'),
                }}
              />
            </a>
          ))}
          <div className="p-3">
            <a
              href={`/search?q=${encodeURIComponent(query.trim())}`}
              className="block w-full text-center py-2 font-medium text-accent"
            >
              Search More
            </a>
          </div>
        </div>
      )}
    </div>
  );
}
