'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 { moviesApi } from '@/lib/api';
import type { Movie } from '@/types';
import { Skeleton, GridSkeleton } from '@/components/ui/Skeleton';
import { useProfileStore } from '@/stores/profileStore';

export default function MoviesPage() {
  const [activeGenre, setActiveGenre] = useState(() => {
    if (typeof window !== 'undefined') {
      return sessionStorage.getItem('cat_tv_movies_active_genre') || 'all';
    }
    return 'all';
  });
  const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
  const [movies, setMovies] = useState<Movie[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMovies, setLoadingMovies] = useState(false);

  // Load categories once
  useEffect(() => {
    async function loadCategories() {
      try {
        const cats = await moviesApi.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 movie categories:', err);
        setCategories([
          { id: 'all', name: 'Todos' },
          { id: 'favorites', name: '⭐ Mis Favoritos' }
        ]);
      } finally {
        setLoading(false);
      }
    }
    loadCategories();
  }, []);

  // Load movies whenever active category changes
  useEffect(() => {
    async function loadMovies() {
      setLoadingMovies(true);
      try {
        if (activeGenre === 'favorites') {
          const response = await moviesApi.getAll(1, 200);
          const allMovies = response.data || [];
          const profileId = useProfileStore.getState().activeProfile?.id;
          const userFavs = profileId ? useProfileStore.getState().favorites[profileId] || [] : [];
          const favMovies = allMovies.filter(m => userFavs.some((fav: any) => String(fav.itemId) === String(m.id)));
          setMovies(favMovies);
        } else {
          const response = await moviesApi.getAll(1, 100, activeGenre);
          setMovies(response.data || []);
        }
      } catch (err) {
        console.error('Error loading movies:', err);
      } finally {
        setLoadingMovies(false);
      }
    }
    loadMovies();
  }, [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="movie" />
      </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">🎬 Películas</h1>
        <p className="text-white/40 text-sm mt-1">{movies.length} películas disponibles</p>
      </motion.div>

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

      {loadingMovies ? (
        <GridSkeleton count={12} type="movie" />
      ) : (
        <ContentGrid
          items={movies}
          type="movie"
        />
      )}
    </div>
  );
}
