'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import HeroBanner from '@/components/content/HeroBanner';
import ContentRow from '@/components/content/ContentRow';
import ContinueWatchingRow from '@/components/content/ContinueWatchingRow';
import { channelsApi, moviesApi, seriesApi } from '@/lib/api';
import type { Movie, Series, Channel } from '@/types';
import { HomeSkeleton } from '@/components/ui/Skeleton';

export default function HomePage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [liveChannels, setLiveChannels] = useState<Channel[]>([]);
  const [popularMovies, setPopularMovies] = useState<Movie[]>([]);
  const [popularSeries, setPopularSeries] = useState<Series[]>([]);
  const [featuredItems, setFeaturedItems] = useState<(Movie | Series)[]>([]);

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

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

        // Helper to get unique items by posterUrl or title
        const getUniqueItems = (list: any[], limit: number) => {
          const seenImages = new Set<string>();
          const seenTitles = new Set<string>();
          const unique: any[] = [];
          
          for (const item of list) {
            if (unique.length >= limit) break;
            
            const img = (item.posterUrl || item.backdropUrl || item.logoUrl || '').trim();
            const title = (item.title || item.name || '').toLowerCase().trim();
            
            // Skip if the image is empty, or if we've already seen this image or title
            if (img && seenImages.has(img)) continue;
            if (title && seenTitles.has(title)) continue;
            
            if (img) seenImages.add(img);
            if (title) seenTitles.add(title);
            unique.push(item);
          }
          
          // If we didn't fill the limit because of filtering, fallback to original slice
          if (unique.length < Math.min(limit, list.length)) {
            const fallback: any[] = [];
            for (const item of list) {
              if (fallback.length >= limit) break;
              fallback.push(item);
            }
            return fallback;
          }
          return unique;
        };

        const uniqueChannels = getUniqueItems(channels, 15);
        const uniqueMovies = getUniqueItems(moviesList, 15);
        const uniqueSeries = getUniqueItems(seriesList, 15);

        setLiveChannels(uniqueChannels);
        setPopularMovies(uniqueMovies);
        setPopularSeries(uniqueSeries);

        // Mix movies and series for a rotating hero banner
        const featuredMoviesSrc = getUniqueItems(moviesList, 5);
        const featuredSeriesSrc = getUniqueItems(seriesList, 5);
        const mixed = [
          ...featuredMoviesSrc.slice(0, 3),
          ...featuredSeriesSrc.slice(0, 2)
        ];
        setFeaturedItems(getUniqueItems(mixed, 5));
      } catch (err) {
        console.error('Error loading home data:', err);
      } finally {
        setLoading(false);
      }
    }
    loadHomeData();
  }, []);

  // World Cup Notification simulation based on real-time EPG data
  useEffect(() => {
    if (loading) return;

    // Check if there is an active sports channel showing a match according to the EPG
    const activeMatchChannel = liveChannels.find(ch => {
      const isSportsCat = 
        ch.category?.name?.toLowerCase().includes('deport') || 
        ch.category?.name?.toLowerCase().includes('sport') ||
        ch.name.toLowerCase().includes('espn') ||
        ch.name.toLowerCase().includes('fox') ||
        ch.name.toLowerCase().includes('directv') ||
        ch.name.toLowerCase().includes('win sports') ||
        ch.name.toLowerCase().includes('tudn') ||
        ch.name.toLowerCase().includes('bein') ||
        ch.name.toLowerCase().includes('sports');
                          
      if (!isSportsCat) return false;

      const program = ch.currentProgram?.toLowerCase() || '';
      return (
        program.includes('vs') || 
        program.includes('mundial') || 
        program.includes('copa') || 
        program.includes('futbol') || 
        program.includes('soccer') || 
        program.includes('world cup') ||
        program.includes('partido') ||
        program.includes('fifa')
      );
    });

    // Only show notification if there is an actual live match in the EPG!
    if (!activeMatchChannel) return;

    const timer = setTimeout(() => {
      toast.custom((t) => (
        <div
          className={`${
            t.visible ? 'animate-enter' : 'animate-leave'
          } max-w-md w-full bg-dark-200/95 backdrop-blur-md border border-primary/30 shadow-2xl shadow-primary/10 rounded-xl pointer-events-auto flex p-4 ring-1 ring-black ring-opacity-5`}
        >
          <div className="flex-1 w-0">
            <div className="flex items-start">
              <div className="flex-shrink-0 pt-0.5">
                <span className="text-2xl">🏆</span>
              </div>
              <div className="ml-3 flex-1 font-sans">
                <p className="text-sm font-bold text-white flex items-center gap-1.5">
                  ¡MUNDIAL EN VIVO!
                  <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
                </p>
                <p className="mt-1 text-xs text-white/70">
                  El partido <span className="font-bold text-primary">{activeMatchChannel.currentProgram}</span> ya comenzó en <span className="font-semibold text-white">{activeMatchChannel.name}</span>.
                </p>
              </div>
            </div>
          </div>
          <div className="flex border-l border-white/10 pl-3 ml-3 items-center font-sans">
            <button
              onClick={() => {
                toast.dismiss(t.id);
                router.push(`/tv/${activeMatchChannel.id}`);
              }}
              className="px-3 py-1.5 rounded-lg bg-primary hover:bg-primary/90 text-white text-xs font-bold transition-colors cursor-pointer border-0"
            >
              Ver Ahora
            </button>
          </div>
        </div>
      ), { duration: 10000 });
    }, 5000);

    return () => clearTimeout(timer);
  }, [loading, liveChannels, router]);

  if (loading) {
    return <HomeSkeleton />;
  }

  return (
    <div className="-m-4 lg:-m-6">
      {/* Hero Banner */}
      {featuredItems.length > 0 ? (
        <HeroBanner items={featuredItems} type="movie" />
      ) : (
        <div className="h-[40vh] bg-dark-200 flex items-center justify-center border-b border-white/5">
          <p className="text-white/40">Sin contenido destacado</p>
        </div>
      )}

      {/* Content rows */}
      <div className="px-4 lg:px-6 space-y-8 pb-12 -mt-8 relative z-10">
        <ContinueWatchingRow />

        {liveChannels.length > 0 && (
          <ContentRow
            title="📺 TV en Vivo"
            items={liveChannels}
            type="channel"
          />
        )}

        {popularMovies.length > 0 && (
          <ContentRow
            title="🎬 Películas Populares"
            items={popularMovies}
            type="movie"
          />
        )}

        {popularSeries.length > 0 && (
          <ContentRow
            title="📺 Series Populares"
            items={popularSeries}
            type="series"
          />
        )}
      </div>
    </div>
  );
}
