import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Movie, User } from '@shared/schema';
import { Link, useLocation } from 'wouter';
import Navbar from '@/components/navbar';
import Footer from '@/components/footer';
import HeroSection from '@/components/hero-section';
import MovieCard from '@/components/movie-card';
import GenreFilter from '@/components/genre-filter';
import { Loader2 } from 'lucide-react';
import { getQueryFn, apiRequest } from '@/lib/queryClient';

interface HomePageProps {
  searchQuery?: string;
}

export default function HomePage() {
  const [selectedGenre, setSelectedGenre] = useState('');
  const [featuredMovie, setFeaturedMovie] = useState<Movie | null>(null);
  const [filteredMovies, setFilteredMovies] = useState<Movie[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [location, navigate] = useLocation();
  
  // Fetch current user if logged in
  const { data: user } = useQuery<User | null>({
    queryKey: ['/api/user'],
    queryFn: getQueryFn({ on401: "returnNull" }),
  });
  
  // Fetch all movies
  const { data: movies, isLoading, error } = useQuery<Movie[]>({
    queryKey: ['/api/movies'],
  });
  
  // Fetch translated movies
  const { data: translatedMovies } = useQuery<Movie[]>({
    queryKey: ['/api/movies/translated'],
  });
  
  // Fetch non-translated movies
  const { data: nonTranslatedMovies } = useQuery<Movie[]>({
    queryKey: ['/api/movies/non-translated'],
  });
  
  // Extract unique genres from movies
  const genres = movies 
    ? Array.from(new Set(movies.map(movie => movie.genre)))
    : [];
  
  // Set featured movie and filter movies by genre
  useEffect(() => {
    if (movies && movies.length > 0) {
      // Pick a random movie to feature
      const randomIndex = Math.floor(Math.random() * movies.length);
      setFeaturedMovie(movies[randomIndex]);
      
      // Filter movies by genre if a genre is selected
      if (selectedGenre) {
        setFilteredMovies(movies.filter(movie => movie.genre === selectedGenre));
      } else {
        setFilteredMovies(movies);
      }
    }
  }, [movies, selectedGenre]);
  
  // Process search from props
  useEffect(() => {
    if (movies && searchQuery) {
      const lowercaseQuery = searchQuery.toLowerCase();
      const results = movies.filter(movie => 
        movie.title.toLowerCase().includes(lowercaseQuery) ||
        movie.description.toLowerCase().includes(lowercaseQuery) ||
        movie.genre.toLowerCase().includes(lowercaseQuery) ||
        movie.language.toLowerCase().includes(lowercaseQuery) ||
        (movie.vjName && movie.vjName.toLowerCase().includes(lowercaseQuery))
      );
      setFilteredMovies(results);
    }
  }, [movies, searchQuery]);
  
  // Handle genre filter change
  const handleGenreChange = (genre: string) => {
    setSelectedGenre(genre);
  };
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-10 w-10 animate-spin text-primary" />
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-500">Error loading movies</h1>
          <p className="text-gray-400">{(error as Error).message}</p>
        </div>
      </div>
    );
  }
  
  // Handle search form submissions
  const handleSearch = (query: string) => {
    setSearchQuery(query);
  };
  
  // Handle logout
  const handleLogout = async () => {
    try {
      await apiRequest('POST', '/api/logout');
      // Force refresh to update authentication state
      window.location.href = '/';
    } catch (error) {
      console.error('Failed to logout:', error);
    }
  };

  return (
    <div>
      <Navbar 
        user={user}
        onLogout={handleLogout}
        onSearch={handleSearch}
      />
      
      {/* Hero Section */}
      {featuredMovie && <HeroSection movie={featuredMovie} />}
      
      {/* Main Content */}
      <div className="py-6">
        {/* Translated Movies Section */}
        {translatedMovies && translatedMovies.length > 0 && (
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-white">Translated Movies</h2>
              <Link href="/translated-movies" className="text-primary hover:text-accent">View All</Link>
            </div>
            
            {/* Scrollable movie cards container */}
            <div className="flex space-x-4 overflow-x-auto pb-4 category-scroll">
              {translatedMovies.map(movie => (
                <MovieCard key={movie.id} movie={movie} />
              ))}
            </div>
          </div>
        )}
        
        {/* Non-Translated Movies Section */}
        {nonTranslatedMovies && nonTranslatedMovies.length > 0 && (
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-white">Non-Translated Movies</h2>
              <Link href="/non-translated-movies" className="text-primary hover:text-accent">View All</Link>
            </div>
            
            {/* Scrollable movie cards container */}
            <div className="flex space-x-4 overflow-x-auto pb-4 category-scroll">
              {nonTranslatedMovies.map(movie => (
                <MovieCard key={movie.id} movie={movie} />
              ))}
            </div>
          </div>
        )}
        
        {/* Genres Section */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-white">
              {searchQuery ? `Search Results: "${searchQuery}"` : "Trending by Genre"}
            </h2>
            {!searchQuery && <span className="text-primary hover:text-accent">View All Genres</span>}
          </div>
          
          {!searchQuery && <GenreFilter genres={genres} onFilterChange={handleGenreChange} />}
          
          {/* Filtered Movies Grid */}
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
            {filteredMovies.map(movie => (
              <MovieCard key={movie.id} movie={movie} compact />
            ))}
          </div>
          
          {filteredMovies.length === 0 && (
            <div className="text-center py-12">
              <h3 className="text-xl text-gray-400">
                {searchQuery ? `No results found for "${searchQuery}"` : "No movies found in this genre"}
              </h3>
            </div>
          )}
        </div>
      </div>
      
      <Footer />
    </div>
  );
}
