import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Movie } from '@shared/schema';
import Navbar from '@/components/navbar';
import Footer from '@/components/footer';
import MovieCard from '@/components/movie-card';
import GenreFilter from '@/components/genre-filter';
import { Loader2 } from 'lucide-react';
import { Input } from '@/components/ui/input';

export default function TranslatedMovies() {
  const [selectedGenre, setSelectedGenre] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedVJ, setSelectedVJ] = useState('');
  
  // Fetch translated movies
  const { data: movies, isLoading, error } = useQuery<Movie[]>({
    queryKey: ['/api/movies/translated'],
  });
  
  // Extract unique genres and VJ names
  const genres = movies 
    ? [...new Set(movies.map(movie => movie.genre))]
    : [];
    
  const vjNames = movies 
    ? [...new Set(movies.filter(movie => movie.vjName).map(movie => movie.vjName!))]
    : [];
  
  // Filter movies
  const filteredMovies = movies?.filter(movie => {
    // Genre filter
    if (selectedGenre && movie.genre !== selectedGenre) {
      return false;
    }
    
    // VJ filter
    if (selectedVJ && movie.vjName !== selectedVJ) {
      return false;
    }
    
    // Search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        movie.title.toLowerCase().includes(query) ||
        (movie.vjName && movie.vjName.toLowerCase().includes(query)) ||
        movie.description.toLowerCase().includes(query)
      );
    }
    
    return true;
  });
  
  // Handle search
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
  };
  
  // Handle VJ filter
  const handleVJFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedVJ(e.target.value);
  };
  
  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>
    );
  }
  
  return (
    <div>
      <Navbar />
      
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <h1 className="text-3xl font-bold text-white mb-6">Translated Movies</h1>
        
        {/* Filters and Search */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <div>
            <Input
              type="text"
              placeholder="Search movies or VJs..."
              className="bg-gray-800 border-gray-700 text-white"
              value={searchQuery}
              onChange={handleSearch}
            />
          </div>
          
          <div>
            <select 
              className="w-full bg-gray-800 border border-gray-700 rounded-md py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-primary"
              value={selectedVJ}
              onChange={handleVJFilterChange}
            >
              <option value="">All VJs</option>
              {vjNames.map(vj => (
                <option key={vj} value={vj}>{vj}</option>
              ))}
            </select>
          </div>
        </div>
        
        {/* Genre Filter */}
        <GenreFilter genres={genres} onFilterChange={setSelectedGenre} />
        
        {/* Movies Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-6">
          {filteredMovies?.map(movie => (
            <MovieCard key={movie.id} movie={movie} />
          ))}
        </div>
        
        {/* Empty State */}
        {filteredMovies?.length === 0 && (
          <div className="text-center py-12">
            <h3 className="text-xl text-gray-400">No movies found matching your filters</h3>
          </div>
        )}
      </div>
      
      <Footer />
    </div>
  );
}
