import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Search, X } from "lucide-react";
import { Link } from "wouter";
import type { MediaOutlet, Article } from "@shared/schema";

interface SearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

interface SearchResults {
  outlets: MediaOutlet[];
  articles: Article[];
}

export default function SearchModal({ isOpen, onClose }: SearchModalProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [debouncedQuery, setDebouncedQuery] = useState("");

  // Debounce search query
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedQuery(searchQuery);
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery]);

  const { data: searchResults, isLoading } = useQuery<SearchResults>({
    queryKey: ["/api/search", debouncedQuery],
    queryFn: async () => {
      if (!debouncedQuery.trim()) {
        return { outlets: [], articles: [] };
      }
      const res = await fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`);
      if (!res.ok) {
        throw new Error(`${res.status}: ${res.statusText}`);
      }
      return res.json();
    },
    enabled: !!debouncedQuery.trim(),
  });

  const totalResults = (searchResults?.outlets.length || 0) + (searchResults?.articles.length || 0);

  const handleClose = () => {
    setSearchQuery("");
    setDebouncedQuery("");
    onClose();
  };

  const handleLinkClick = () => {
    handleClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden p-0 [&>button]:hidden">
        <DialogTitle className="sr-only">Search Articles and Media Outlets</DialogTitle>
        {/* Search Header */}
        <div className="flex items-center gap-2 p-3 border-b">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              type="text"
              placeholder="Search articles..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 pr-4 border-2 border-blue-200 focus:border-blue-400"
              data-testid="search-modal-input"
              autoFocus
            />
          </div>
          <button
            onClick={handleClose}
            className="p-2 hover:bg-gray-100 rounded transition-colors"
            data-testid="search-modal-close"
            aria-label="Close"
          >
            <X className="h-4 w-4 text-gray-500" />
          </button>
        </div>

        {/* Search Results */}
        <div className="flex-1 overflow-y-auto p-3">
          {!debouncedQuery.trim() ? (
            /* Empty State */
            <div className="text-center py-8 text-gray-500">
              <p className="text-sm">Start typing to search articles and outlets</p>
            </div>
          ) : isLoading ? (
            /* Loading State */
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="animate-pulse">
                  <div className="h-4 bg-gray-200 rounded w-3/4 mb-1"></div>
                  <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                </div>
              ))}
            </div>
          ) : totalResults === 0 ? (
            /* No Results */
            <div className="text-center py-8 text-gray-500">
              <p className="text-sm">No results found for "{debouncedQuery}"</p>
              <p className="text-xs mt-1">Try a different search term</p>
            </div>
          ) : (
            /* Search Results */
            <>
              <div className="mb-2 text-xs text-gray-500">
                {totalResults} results found
              </div>

              {/* Outlets Section */}
              {searchResults && searchResults.outlets.length > 0 && (
                <div className="mb-3">
                  <h3 className="text-sm font-semibold text-gray-700 mb-2">
                    Outlets ({searchResults.outlets.length})
                  </h3>
                  <div className="space-y-2">
                    {searchResults.outlets.map((outlet) => (
                      <Link
                        key={outlet.id}
                        href={`/media/${outlet.slug}`}
                        onClick={handleLinkClick}
                        data-testid={`search-outlet-${outlet.id}`}
                      >
                        <div className="flex items-center gap-2 p-2 hover:bg-gray-50 rounded border cursor-pointer">
                          <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center overflow-hidden flex-shrink-0">
                            {outlet.imageUrl ? (
                              <img
                                src={outlet.imageUrl}
                                alt={outlet.name}
                                className="w-full h-full object-cover"
                              />
                            ) : (
                              <span className="text-gray-600 font-medium text-xs">
                                {outlet.name.charAt(0)}
                              </span>
                            )}
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-1.5 mb-0.5">
                              <h4 className="font-medium text-sm text-gray-900 truncate">
                                {outlet.name}
                              </h4>
                              <Badge variant="secondary" className="text-xs py-0">
                                {outlet.category}
                              </Badge>
                            </div>
                            <p className="text-xs text-gray-500 truncate">
                              {outlet.description || "Media Outlet"}
                            </p>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              )}

              {/* Articles Section */}
              {searchResults && searchResults.articles.length > 0 && (
                <div>
                  <h3 className="text-sm font-semibold text-gray-700 mb-2">
                    Articles ({searchResults.articles.length})
                  </h3>
                  <div className="space-y-2">
                    {searchResults.articles.map((article) => (
                      <Link
                        key={article.id}
                        href={`/articles/${article.slug}`}
                        onClick={handleLinkClick}
                        data-testid={`search-article-${article.id}`}
                      >
                        <div className="flex items-start gap-2 p-2 hover:bg-gray-50 rounded border cursor-pointer">
                          {article.imageUrl && (
                            <div className="w-12 h-9 rounded bg-gray-100 overflow-hidden flex-shrink-0">
                              <img
                                src={article.imageUrl}
                                alt={article.title}
                                className="w-full h-full object-cover"
                              />
                            </div>
                          )}
                          <div className="flex-1 min-w-0">
                            <h4 className="font-medium text-sm text-gray-900 line-clamp-2 mb-0.5">
                              {article.title}
                            </h4>
                            <p className="text-xs text-gray-500 line-clamp-1">
                              {article.excerpt || ""}
                            </p>
                            {article.publishedAt && (
                              <p className="text-xs text-gray-400 mt-0.5">
                                {new Date(article.publishedAt).toLocaleDateString('en-US', {
                                  month: 'short',
                                  day: 'numeric',
                                  year: 'numeric'
                                })}
                              </p>
                            )}
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}