
import React, { useEffect, useState } from 'react';
import PageHeader from '../components/PageHeader';
import ContentGrid from '../components/ContentGrid';
import { getAllMovies, getMovieCard } from '../lib/api';
import { useToast } from '@/hooks/use-toast';
import { useSearchParams } from 'react-router-dom';

const MoviesPage = () => {
  const [loading, setLoading] = useState(true);
  const [movies, setMovies] = useState<any[]>([]);
  const [searchParams] = useSearchParams();
  const genreFilter = searchParams.get('genre');
  const { toast } = useToast();

  useEffect(() => {
    const fetchMovies = async () => {
      try {
        setLoading(true);
        const allMovies = await getAllMovies();
        
        // For each movie, get its card info for display
        const moviePromises = allMovies.slice(0, 30).map(async (movie: any) => {
          try {
            const movieInfo = await getMovieCard(movie.title);
            if (movieInfo) {
              return {
                type: 'movie',
                title: movie.title,
                image: movieInfo.image,
                description: movieInfo.overview,
                genre: movieInfo.genres?.map((g: any) => g.name) || [],
                year: movieInfo.year
              };
            }
            return null;
          } catch (error) {
            console.error(`Error fetching movie info for ${movie.title}:`, error);
            return null;
          }
        });
        
        let moviesData = await Promise.all(moviePromises);
        moviesData = moviesData.filter(movie => movie !== null);
        
        // Apply genre filter if present
        if (genreFilter) {
          moviesData = moviesData.filter(movie => 
            movie.genre.some((g: string) => g.toLowerCase() === genreFilter.toLowerCase())
          );
        }
        
        setMovies(moviesData);
      } catch (error) {
        console.error('Error fetching movies:', error);
        toast({
          title: "Error loading movies",
          description: "Please try again later",
          variant: "destructive"
        });
      } finally {
        setLoading(false);
      }
    };
    
    fetchMovies();
  }, [genreFilter, toast]);

  return (
    <div className="pb-12">
      <PageHeader 
        title={genreFilter ? `${genreFilter} Movies` : "All Movies"} 
        subtitle={`${movies.length} titles available`}
      />
      
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-netflix-red"></div>
        </div>
      ) : (
        <ContentGrid 
          items={movies} 
          emptyMessage={genreFilter 
            ? `No movies found in the ${genreFilter} genre` 
            : "No movies available"}
        />
      )}
    </div>
  );
};

export default MoviesPage;
