import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { type Video } from "@shared/schema";
import VideoCard from "@/components/video-card";
import { Link } from "wouter";
import { Input } from "@/components/ui/input";
import { Search, Menu, X } from "lucide-react";

interface VideosResponse {
  videos: Video[];
  total: number;
  hasMore: boolean;
}

export default function Home() {
  const [searchQuery, setSearchQuery] = useState("");
  const [allVideos, setAllVideos] = useState<Video[]>([]);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  // Fetch videos with optimized loading
  const { data: videosResponse, isLoading, refetch } = useQuery<VideosResponse>({
    queryKey: ["/api/videos", { 
      limit: 150,
      offset: 0, 
      search: searchQuery || undefined
    }],
    queryFn: async ({ queryKey }) => {
      const [, params] = queryKey as [string, any];
      const searchParams = new URLSearchParams();
      
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) {
          searchParams.append(key, String(value));
        }
      });

      const response = await fetch(`/api/videos?${searchParams}`);
      if (!response.ok) {
        throw new Error('Failed to fetch videos');
      }
      return response.json();
    },
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false
  });

  // Update videos when new data comes in
  useEffect(() => {
    if (videosResponse) {
      setAllVideos(videosResponse.videos);
    }
  }, [videosResponse]);

  // Only refetch when search changes
  useEffect(() => {
    if (searchQuery !== undefined) {
      refetch();
    }
  }, [searchQuery, refetch]);

  const handleVideoClick = (video: Video) => {
    window.location.href = `/video/${video.id}`;
  };

  return (
    <div style={{minHeight: '100vh', background: 'linear-gradient(135deg, hsl(250, 50%, 15%) 0%, hsl(240, 30%, 25%) 100%)', color: 'white'}}>
      {/* Header */}
      <header className="sticky top-0 z-50 bg-black/30 backdrop-blur-md border-b border-white/10">
        <div className="container py-4">
          <div className="flex items-center justify-between">
            {/* Logo */}
            <Link href="/" className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                <div className="w-0 h-0 border-l-[12px] border-l-white border-y-[8px] border-y-transparent ml-1"></div>
              </div>
              <h1 className="text-2xl font-bold text-white">go4.video</h1>
            </Link>

            {/* Navigation & Search */}
            <div className="flex items-center gap-6">
              {/* Desktop navigation */}
              <div className="hidden md:flex items-center space-x-6">
                <nav className="flex space-x-6">
                  <Link href="/" className="text-white/80 hover:text-white transition-colors">
                    Home
                  </Link>
                  <Link href="/folx-stadl" className="text-white/80 hover:text-white transition-colors">
                    FOLX STADL
                  </Link>
                </nav>
                
                <div className="relative">
                  <Input
                    type="search"
                    placeholder="Videos suchen..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="bg-white/10 border-white/20 text-white placeholder-white/50 w-64"
                  />
                  <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-white/50 w-4 h-4" />
                </div>
              </div>

              {/* Mobile menu button */}
              <button
                onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                className="md:hidden p-2 text-white"
              >
                {isMobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
              </button>
            </div>
          </div>

          {/* Mobile Menu */}
          {isMobileMenuOpen && (
            <div className="md:hidden mt-4 pt-4 border-t border-white/20">
              <nav className="flex flex-col space-y-3 mb-4">
                <Link href="/" className="text-white/80 hover:text-white">Home</Link>
                <Link href="/folx-stadl" className="text-white/80 hover:text-white">FOLX STADL</Link>
              </nav>
              <div className="relative">
                <Input
                  type="search"
                  placeholder="Suchen..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="bg-white/10 border-white/20 text-white placeholder-white/50 w-full"
                />
                <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-white/50 w-4 h-4" />
              </div>
            </div>
          )}
        </div>
      </header>

      {/* Main Content */}
      <main className="container py-8">
        {isLoading ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {Array.from({ length: 18 }).map((_, index) => (
              <div key={index} className="animate-pulse">
                <div className="bg-white/10 aspect-video rounded-lg mb-3"></div>
                <div className="space-y-2">
                  <div className="h-4 bg-white/10 rounded w-3/4"></div>
                  <div className="h-3 bg-white/10 rounded w-1/2"></div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {allVideos.map((video) => (
              <VideoCard
                key={video.id}
                video={video}
                onClick={handleVideoClick}
                className="hover:scale-105 transition-transform duration-200"
              />
            ))}
          </div>
        )}

        {allVideos.length === 0 && !isLoading && (
          <div className="text-center py-12">
            <div className="text-white/60 text-lg">Keine Videos gefunden</div>
          </div>
        )}
      </main>
    </div>
  );
}