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

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

  useEffect(() => {
    const fetchTvShows = async () => {
      try {
        setLoading(true);
        const allTvShows = await getAllTvShows();
        
        // For each tv show, get its card info for display
        const tvShowPromises = allTvShows.slice(0, 30).map(async (show: any) => {
          try {
            const showInfo = await getTvShowCard(show.title);
            if (showInfo) {
              return {
                type: 'tvshow',
                title: show.title,
                image: showInfo.image,
                description: showInfo.overview,
                genre: showInfo.genres?.map((g: any) => g.name) || [],
                year: showInfo.year,
                episodeCount: show.episodeCount
              };
            }
            return null;
          } catch (error) {
            console.error(`Error fetching tv show info for ${show.title}:`, error);
            return null;
          }
        });
        
        let tvShowsData = await Promise.all(tvShowPromises);
        tvShowsData = tvShowsData.filter(show => show !== null);
        
        // Apply genre filter if present
        if (genreFilter) {
          tvShowsData = tvShowsData.filter(show => 
            show.genre.some((g: string) => g.toLowerCase() === genreFilter.toLowerCase())
          );
        }
        
        setTvShows(tvShowsData);
      } catch (error) {
        console.error('Error fetching TV shows:', error);
        toast({
          title: "Error loading TV shows",
          description: "Please try again later",
          variant: "destructive"
        });
      } finally {
        setLoading(false);
      }
    };
    
    fetchTvShows();
  }, [genreFilter, toast]);

  return (
    <div className="pb-12">
      <PageHeader 
        title={genreFilter ? `${genreFilter} TV Shows` : "All TV Shows"} 
        subtitle={`${tvShows.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={tvShows}
          emptyMessage={genreFilter 
            ? `No TV shows found in the ${genreFilter} genre` 
            : "No TV shows available"}
        />
      )}
    </div>
  );
};

export default TvShowsPage;
