import React, { useEffect, useState } from 'react';
import { searchTopics } from '@/lib/services/search';

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

interface SearchOutputProps {
  query: string;
  showLoadMore?: boolean;
}

export default function SearchOutput({ query, showLoadMore = false }: SearchOutputProps) {
  const [results, setResults] = useState<SearchAnswer[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [cannotSearchMore, setCannotSearchMore] = useState(false);

  useEffect(() => {
    searchTopics(query, { useWebSearch: true })
      .then(response => {
        setResults(response.results);
        setCannotSearchMore(response.cannot_search_more);
      })
      .finally(() => setLoading(false));
  }, [query]);

  const handleLoadMore = async () => {
    setLoadingMore(true);
    try {
      const response = await searchTopics(query, { pastResults: results, useWebSearch: true });
      setResults(prev => [...prev, ...response.results]);
      setCannotSearchMore(response.cannot_search_more);
    } catch (error) {
      console.error('Failed to load more results:', error);
    } finally {
      setLoadingMore(false);
    }
  };

  if (loading) return <div className="text-center py-8">Loading...</div>;
  if (!results.length) return <div className="text-center py-8">No results</div>;

  return (
    <div className="w-full">
      <div className="divide-y divide-border">
        {results.map((result, i) => (
          <a
            key={i}
            href={result.url}
            className="block px-4 py-4 hover:bg-muted/30 transition-colors"
          >
            <h3 className="font-medium text-foreground mb-1">{result.title.replace(/_/g, ' ')}</h3>
            <p
              className="text-sm text-muted-foreground leading-relaxed"
              dangerouslySetInnerHTML={{
                __html: result.excerpt.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>'),
              }}
            />
          </a>
        ))}
      </div>

      {showLoadMore && (
        <div className="p-4 border-t border-border">
          <button
            onClick={handleLoadMore}
            disabled={loadingMore || cannotSearchMore}
            className={`w-full text-center py-2 font-medium transition-colors ${
              loadingMore || cannotSearchMore
                ? 'text-muted-foreground cursor-not-allowed'
                : 'text-accent hover:bg-muted/30'
            }`}
          >
            {loadingMore ? 'Loading...' : cannotSearchMore ? 'Search Ended' : 'Load More'}
          </button>
        </div>
      )}
    </div>
  );
}
