'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import CategoryTabs from '@/components/content/CategoryTabs';
import ContentGrid from '@/components/content/ContentGrid';
import { seriesApi } from '@/lib/api';
import type { Series } from '@/types';
import { Skeleton, GridSkeleton } from '@/components/ui/Skeleton';
import { useProfileStore } from '@/stores/profileStore';

export default function SeriesPage() {
  const [activeGenre, setActiveGenre] = useState(() => {
    if (typeof window !== 'undefined') {
      return sessionStorage.getItem('cat_tv_series_active_genre') || 'all';
    }
    return 'all';
  });
  const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
  const [seriesList, setSeriesList] = useState<Series[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingSeries, setLoadingSeries] = useState(false);

  // Load categories once
  useEffect(() => {
    async function loadCategories() {
      try {
        const cats = await seriesApi.getCategories();
        setCategories([
          { id: 'all', name: 'Todos' },
          { id: 'favorites', name: '⭐ Mis Favoritos' },
          ...cats.map(c => ({ id: c.id, name: c.name }))
        ]);
      } catch (err) {
        console.error('Error loading series categories:', err);
        setCategories([
          { id: 'all', name: 'Todos' },
          { id: 'favorites', name: '⭐ Mis Favoritos' }
        ]);
      } finally {
        setLoading(false);
      }
    }
    loadCategories();
  }, []);

  // Load series whenever active category changes
  useEffect(() => {
    async function loadSeries() {
      setLoadingSeries(true);
      try {
        if (activeGenre === 'favorites') {
          const response = await seriesApi.getAll(1, 200);
          const allSeries = response.data || [];
          const profileId = useProfileStore.getState().activeProfile?.id;
          const userFavs = profileId ? useProfileStore.getState().favorites[profileId] || [] : [];
          const favSeries = allSeries.filter(s => userFavs.some((fav: any) => String(fav.itemId) === String(s.id)));
          setSeriesList(favSeries);
        } else {
          const response = await seriesApi.getAll(1, 100, activeGenre);
          setSeriesList(response.data || []);
        }
      } catch (err) {
        console.error('Error loading series:', err);
      } finally {
        setLoadingSeries(false);
      }
    }
    loadSeries();
  }, [activeGenre]);

  if (loading) {
    return (
      <div className="space-y-6">
        <div>
          <Skeleton className="h-8 w-48 rounded" />
          <Skeleton className="h-4 w-32 rounded mt-1" />
        </div>
        <Skeleton className="h-10 w-full rounded-lg" />
        <GridSkeleton count={12} type="series" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <h1 className="text-2xl md:text-3xl font-bold text-white">📺 Series</h1>
        <p className="text-white/40 text-sm mt-1">{seriesList.length} series disponibles</p>
      </motion.div>

      {categories.length > 1 && (
        <CategoryTabs
          categories={categories}
          activeCategory={activeGenre}
          onChange={(genreId) => {
            setActiveGenre(genreId);
            if (typeof window !== 'undefined') {
              sessionStorage.setItem('cat_tv_series_active_genre', genreId);
            }
          }}
        />
      )}

      {loadingSeries ? (
        <GridSkeleton count={12} type="series" />
      ) : (
        <ContentGrid
          items={seriesList}
          type="series"
        />
      )}
    </div>
  );
}
