import { useQuery } from "@tanstack/react-query";
import { useState, useEffect, useRef } from "react";
import { Link, useSearch, useLocation } from "wouter";
import { Search, Play, FileText, ArrowLeft } from "lucide-react";
import { usePageMeta } from "@/hooks/use-page-meta";
import Header from "@/components/header";

interface SearchResult {
  articles: {
    id: number;
    title: string;
    slug: string;
    excerpt: string;
    coverImage: string;
    category: string;
    author: string;
    publishedAt: string;
  }[];
  videos: {
    guid: string;
    title: string;
    description: string;
    thumbnail: string;
    embedUrl: string;
  }[];
}

export default function SearchPage() {
  usePageMeta("Suche - Volksmusik & Schlager", "Durchsuchen Sie FOLX TV nach Volksmusik- und Schlager-Inhalten.");
  const searchString = useSearch();
  const initialQuery = new URLSearchParams(searchString).get("q") || "";
  const [query, setQuery] = useState(initialQuery);
  const [searchTerm, setSearchTerm] = useState(initialQuery);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const q = new URLSearchParams(searchString).get("q") || "";
    if (q && q !== searchTerm) {
      setQuery(q);
      setSearchTerm(q);
    }
  }, [searchString]);

  const handleQueryChange = (val: string) => {
    setQuery(val);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      if (val.trim().length >= 2) {
        setSearchTerm(val.trim());
      }
    }, 500);
  };

  const { data, isLoading } = useQuery<SearchResult>({
    queryKey: ["/api/search", searchTerm],
    queryFn: async () => {
      if (!searchTerm || searchTerm.length < 2) return { articles: [], videos: [] };
      const resp = await fetch(`/api/search?q=${encodeURIComponent(searchTerm)}`);
      return resp.json();
    },
    enabled: searchTerm.length >= 2,
  });

  const [, navigate] = useLocation();

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (query.trim().length >= 2) {
      setSearchTerm(query.trim());
    }
  };

  const totalResults = (data?.articles?.length || 0) + (data?.videos?.length || 0);

  return (
    <div className="min-h-screen bg-background" data-testid="page-search">
      <Header />
      <main className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <Link href="/">
          <button className="flex items-center gap-1 text-muted-foreground hover:text-foreground text-sm mb-4 transition-colors" data-testid="link-back-home">
            <ArrowLeft className="w-4 h-4" />
            Zurück
          </button>
        </Link>

        <form onSubmit={handleSubmit} className="mb-6" data-testid="form-search">
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
            <input
              type="text"
              value={query}
              onChange={(e) => handleQueryChange(e.target.value)}
              placeholder="Artikel, Videos, Künstler suchen..."
              className="w-full pl-12 pr-4 py-3 bg-card border border-card-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary text-base"
              autoFocus
              data-testid="input-search"
            />
          </div>
        </form>

        {searchTerm.length >= 2 && (
          <p className="text-muted-foreground text-sm mb-4" data-testid="text-result-count">
            {isLoading ? "Suche läuft..." : `${totalResults} Ergebnis${totalResults !== 1 ? "se" : ""} für "${searchTerm}"`}
          </p>
        )}

        {isLoading && (
          <div className="space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="h-24 bg-card rounded-lg animate-pulse" />
            ))}
          </div>
        )}

        {data && data.articles.length > 0 && (
          <div className="mb-8">
            <h2 className="text-lg font-bold text-foreground mb-3 flex items-center gap-2" data-testid="heading-articles">
              <FileText className="w-5 h-5 text-primary" />
              Artikel ({data.articles.length})
            </h2>
            <div className="space-y-3">
              {data.articles.map((article) => (
                <Link key={article.id} href={`/article/${article.slug}`}>
                  <div className="flex gap-4 bg-card border border-card-border rounded-lg p-3 hover:border-primary/50 transition-colors cursor-pointer" data-testid={`search-article-${article.id}`}>
                    {article.coverImage && (
                      <img
                        src={article.coverImage}
                        alt={article.title}
                        className="w-24 h-24 sm:w-32 sm:h-20 object-cover rounded-md flex-shrink-0"
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      <span className="text-xs text-primary font-medium">{article.category}</span>
                      <h3 className="text-sm font-bold text-card-foreground line-clamp-2 mt-0.5">{article.title}</h3>
                      <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{article.excerpt}</p>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {data && data.videos.length > 0 && (
          <div className="mb-8">
            <h2 className="text-lg font-bold text-foreground mb-3 flex items-center gap-2" data-testid="heading-videos">
              <Play className="w-5 h-5 text-primary" />
              Videos ({data.videos.length})
            </h2>
            <div className="space-y-3">
              {data.videos.map((video) => (
                <a
                  key={video.guid}
                  href={video.embedUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex gap-4 bg-card border border-card-border rounded-lg p-3 hover:border-primary/50 transition-colors cursor-pointer"
                  data-testid={`search-video-${video.guid}`}
                >
                  <div className="relative w-24 h-24 sm:w-32 sm:h-20 flex-shrink-0">
                    <img
                      src={video.thumbnail}
                      alt={video.title}
                      className="w-full h-full object-cover rounded-md"
                    />
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="w-8 h-8 rounded-full bg-primary/80 flex items-center justify-center">
                        <Play className="w-4 h-4 text-white fill-white" />
                      </div>
                    </div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <span className="text-xs text-primary font-medium">Video</span>
                    <h3 className="text-sm font-bold text-card-foreground line-clamp-2 mt-0.5">{video.title}</h3>
                    {video.description && (
                      <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{video.description}</p>
                    )}
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}

        {data && totalResults === 0 && searchTerm.length >= 2 && !isLoading && (
          <div className="text-center py-12" data-testid="text-no-results">
            <Search className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
            <p className="text-muted-foreground">Keine Ergebnisse für "{searchTerm}" gefunden.</p>
            <p className="text-muted-foreground text-sm mt-1">Versuchen Sie einen anderen Suchbegriff.</p>
          </div>
        )}
      </main>
    </div>
  );
}
