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

const favTabs = [
  { id: 'all', name: 'Todos' },
  { id: 'channels', name: '📺 Canales' },
  { id: 'movies', name: '🎬 Películas' },
  { id: 'series', name: '📺 Series' },
];

export default function FavoritesPage() {
  const [activeTab, setActiveTab] = useState('all');
  const [loading, setLoading] = useState(true);
  const [favChannels, setFavChannels] = useState<Channel[]>([]);
  const [favMovies, setFavMovies] = useState<Movie[]>([]);
  const [favSeries, setFavSeries] = useState<Series[]>([]);

  const { activeProfile, favorites } = useProfileStore();
  const profileFavs = activeProfile ? favorites[activeProfile.id] || [] : [];

  useEffect(() => {
    async function loadFavorites() {
      setLoading(true);
      try {
        const [channels, moviesRes, seriesRes] = await Promise.all([
          channelsApi.getAll().catch(() => [] as Channel[]),
          moviesApi.getAll(1, 200).catch(() => ({ data: [] as Movie[] })),
          seriesApi.getAll(1, 200).catch(() => ({ data: [] as Series[] })),
        ]);

        const moviesList = moviesRes.data || [];
        const seriesList = seriesRes.data || [];

        // Filter based on profile favorites
        setFavChannels(channels.filter(ch => profileFavs.includes(String(ch.id))));
        setFavMovies(moviesList.filter(m => profileFavs.includes(String(m.id))));
        setFavSeries(seriesList.filter(s => profileFavs.includes(String(s.id))));
      } catch (err) {
        console.error('Error loading favorites:', err);
      } finally {
        setLoading(false);
      }
    }

    loadFavorites();
  }, [activeProfile, favorites]);

  if (loading) {
    return (
      <div className="flex h-[80vh] items-center justify-center">
        <Spinner size="lg" color="primary" />
      </div>
    );
  }

  const totalFavsCount = favChannels.length + favMovies.length + favSeries.length;

  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">❤️ Mis Favoritos</h1>
        <p className="text-white/40 text-sm mt-1">
          {totalFavsCount} elementos guardados en {activeProfile?.name}
        </p>
      </motion.div>

      <CategoryTabs
        categories={favTabs}
        activeCategory={activeTab}
        onChange={setActiveTab}
      />

      {totalFavsCount === 0 ? (
        <div className="flex h-[40vh] flex-col items-center justify-center gap-4 text-center">
          <p className="text-white/40 italic">Aún no has agregado favoritos en este perfil.</p>
        </div>
      ) : (
        <div className="space-y-8">
          {(activeTab === 'all' || activeTab === 'channels') && favChannels.length > 0 && (
            <div>
              <h2 className="text-lg font-bold text-white mb-4">📺 Canales</h2>
              <ContentGrid items={favChannels} type="channel" />
            </div>
          )}

          {(activeTab === 'all' || activeTab === 'movies') && favMovies.length > 0 && (
            <div>
              <h2 className="text-lg font-bold text-white mb-4">🎬 Películas</h2>
              <ContentGrid items={favMovies} type="movie" />
            </div>
          )}

          {(activeTab === 'all' || activeTab === 'series') && favSeries.length > 0 && (
            <div>
              <h2 className="text-lg font-bold text-white mb-4">📺 Series</h2>
              <ContentGrid items={favSeries} type="series" />
            </div>
          )}
        </div>
      )}
    </div>
  );
}
