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

export default function TVPage() {
  const [activeCategory, setActiveCategory] = useState(() => {
    if (typeof window !== 'undefined') {
      return sessionStorage.getItem('cat_tv_tv_active_category') || 'all';
    }
    return 'all';
  });
  const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
  const [channels, setChannels] = useState<Channel[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingChannels, setLoadingChannels] = useState(false);

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

  // Load channels whenever active category changes
  useEffect(() => {
    async function loadChannels() {
      setLoadingChannels(true);
      try {
        if (activeCategory === 'favorites') {
          const chs = await channelsApi.getAll('all');
          const profileId = useProfileStore.getState().activeProfile?.id;
          const userFavs = profileId ? useProfileStore.getState().favorites[profileId] || [] : [];
          const favChannels = chs.filter(ch => userFavs.some((fav: any) => String(fav.itemId) === String(ch.id)));
          setChannels(favChannels);
        } else {
          const chs = await channelsApi.getAll(activeCategory);
          setChannels(chs);
        }
      } catch (err) {
        console.error('Error loading channels:', err);
      } finally {
        setLoadingChannels(false);
      }
    }
    loadChannels();
  }, [activeCategory]);

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between"
      >
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-white">📺 TV en Vivo</h1>
          <p className="text-white/40 text-sm mt-1">{channels.length} canales disponibles</p>
        </div>
        <div className="flex items-center gap-2 text-xs text-white/40">
          <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
          En vivo
        </div>
      </motion.div>

      {/* Category tabs */}
      {categories.length > 1 && (
        <CategoryTabs
          categories={categories}
          activeCategory={activeCategory}
          onChange={(catId) => {
            setActiveCategory(catId);
            if (typeof window !== 'undefined') {
              sessionStorage.setItem('cat_tv_tv_active_category', catId);
            }
          }}
        />
      )}

      {/* Channel grid */}
      {loadingChannels ? (
        <GridSkeleton count={12} type="channel" />
      ) : (
        <ContentGrid
          items={channels}
          type="channel"
        />
      )}
    </div>
  );
}
