'use client';

import React, { useState, useEffect } from 'react';
import { FiSearch, FiX, FiTv, FiFilm, FiMonitor } from 'react-icons/fi';
import { searchApi, channelsApi, moviesApi, seriesApi } from '@/lib/api';
import { StreamItem } from '@/stores/multiStreamStore';
import Badge from '@/components/ui/Badge';
import Spinner from '@/components/ui/Spinner';

interface AddStreamModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (item: StreamItem) => void;
}

export default function AddStreamModal({ isOpen, onClose, onSelect }: AddStreamModalProps) {
  const [query, setQuery] = useState('');
  const [activeTab, setActiveTab] = useState<'all' | 'tv' | 'movie' | 'series'>('all');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<{
    channels: any[];
    movies: any[];
    series: any[];
  }>({ channels: [], movies: [], series: [] });

  const [recentSearches, setRecentSearches] = useState<string[]>([]);

  // Load recent searches when modal opens
  useEffect(() => {
    if (isOpen && typeof window !== 'undefined') {
      const saved = localStorage.getItem('cat_tv_recent_searches');
      if (saved) {
        try { setRecentSearches(JSON.parse(saved)); } catch (_) {}
      }
    }
  }, [isOpen]);

  const saveQuery = (q: string) => {
    if (!q || q.trim() === '') return;
    const clean = q.trim();
    setRecentSearches((prev) => {
      const filtered = prev.filter((item) => item.toLowerCase() !== clean.toLowerCase());
      const updated = [clean, ...filtered].slice(0, 5);
      localStorage.setItem('cat_tv_recent_searches', JSON.stringify(updated));
      return updated;
    });
  };

  // Load default/recommended items when opening modal or changing tabs
  useEffect(() => {
    if (!isOpen) return;

    async function loadDefaults() {
      setLoading(true);
      try {
        if (query.trim() === '') {
          // Fetch recommended/top content safely (individual catches prevent Promise.all failure)
          const [channels, moviesData, seriesData] = await Promise.all([
            channelsApi.getAll().catch(() => []).then(res => Array.isArray(res) ? res.slice(0, 12) : []),
            moviesApi.getAll(1, 12).catch(() => null).then(res => res?.data || []),
            seriesApi.getAll(1, 12).catch(() => null).then(res => res?.data || []),
          ]);
          setResults({
            channels: channels || [],
            movies: moviesData || [],
            series: seriesData || [],
          });
        } else {
          // Map frontend activeTab to backend API filter query parameters
          const apiFilter = 
            activeTab === 'tv' ? 'channels' : 
            activeTab === 'movie' ? 'movies' : 
            activeTab === 'series' ? 'series' : 'all';

          const searchResult = await searchApi.search(query, apiFilter);
          setResults({
            channels: searchResult.channels || [],
            movies: searchResult.movies || [],
            series: searchResult.series || [],
          });
        }
      } catch (err) {
        console.error('Failed to load content for modal:', err);
      } finally {
        setLoading(false);
      }
    }

    const timer = setTimeout(loadDefaults, query.trim() === '' ? 0 : 400);
    return () => clearTimeout(timer);
  }, [isOpen, query, activeTab]);

  if (!isOpen) return null;

  // Flatten and filter results according to active tab
  const getFilteredList = () => {
    const list: any[] = [];

    if (activeTab === 'all' || activeTab === 'tv') {
      results.channels.forEach(ch => list.push({ ...ch, type: 'tv' }));
    }
    if (activeTab === 'all' || activeTab === 'movie') {
      results.movies.forEach(m => list.push({ ...m, type: 'movie' }));
    }
    if (activeTab === 'all' || activeTab === 'series') {
      results.series.forEach(s => list.push({ ...s, type: 'series' }));
    }

    return list;
  };

  const filteredItems = getFilteredList();

  const handleItemClick = async (item: any) => {
    saveQuery(query);
    if (item.type === 'tv') {
      onSelect({
        id: String(item.id),
        url: item.streamUrl,
        title: item.name,
        type: 'tv',
        posterUrl: item.logoUrl || '',
      });
      onClose();
    } else if (item.type === 'movie') {
      onSelect({
        id: String(item.id),
        url: item.streamUrl || '',
        title: item.title,
        type: 'movie',
        posterUrl: item.posterUrl || item.backdropUrl || '',
      });
      onClose();
    } else if (item.type === 'series') {
      // For series, load details to play the first episode dynamically
      setLoading(true);
      try {
        const details = await seriesApi.getById(item.id);
        const firstSeason = details.seasons?.[0];
        const firstEpisode = firstSeason?.episodes?.[0];

        if (firstEpisode && firstEpisode.streamUrl) {
          onSelect({
            id: String(firstEpisode.id),
            url: firstEpisode.streamUrl,
            title: `${item.title} — T${firstSeason.number} E${firstEpisode.number}: ${firstEpisode.title}`,
            type: 'series',
            posterUrl: details.posterUrl || details.backdropUrl || item.posterUrl || '',
          });
          onClose();
        } else {
          alert('No se encontraron episodios disponibles para esta serie');
        }
      } catch (err) {
        console.error('Error loading series details for multi-stream:', err);
        alert('Error al cargar la serie. Verifica tus credenciales de IPTV.');
      } finally {
        setLoading(false);
      }
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 backdrop-blur-md p-4 animate-fade-in">
      <div className="relative w-full max-w-4xl h-[80vh] bg-neutral-900/90 border border-white/10 rounded-2xl flex flex-col overflow-hidden shadow-2xl">
        
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-white/5">
          <div>
            <h3 className="text-xl font-bold text-white">Añadir otro programa</h3>
            <p className="text-xs text-white/50 mt-1">Busca y añade canales en vivo, películas o series para reproducir en paralelo</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg text-white/50 hover:text-white hover:bg-white/5 transition-all"
          >
            <FiX size={20} />
          </button>
        </div>

        {/* Search Bar & Tabs */}
        <div className="p-5 border-b border-white/5 space-y-4">
          <div className="relative">
            <FiSearch className="absolute left-4 top-1/2 -translate-y-1/2 text-white/40" size={18} />
            <input
              type="text"
              placeholder="Buscar por nombre o categoría..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              className="w-full bg-white/5 border border-white/10 rounded-xl pl-12 pr-4 py-3 text-white placeholder-white/30 focus:outline-none focus:border-primary/50 focus:ring-1 focus:ring-primary/30 transition-all"
              autoFocus
            />
          </div>

          {/* Recent searches history */}
          {query.trim() === '' && recentSearches.length > 0 && (
            <div className="flex items-center gap-2 flex-wrap text-xs">
              <span className="text-[10px] uppercase font-bold text-white/30 tracking-wider">Recientes:</span>
              {recentSearches.map((s, idx) => (
                <button
                  key={idx}
                  onClick={() => setQuery(s)}
                  className="px-3 py-1 bg-white/5 hover:bg-white/10 text-white/60 hover:text-white border border-white/5 rounded-full text-[10px] font-semibold transition-all cursor-pointer"
                >
                  {s}
                </button>
              ))}
            </div>
          )}

          {/* Tab buttons */}
          <div className="flex gap-2">
            {[
              { id: 'all', label: 'Todo', icon: null },
              { id: 'tv', label: 'TV en Vivo', icon: FiTv },
              { id: 'movie', label: 'Películas', icon: FiFilm },
              { id: 'series', label: 'Series', icon: FiMonitor },
            ].map((tab) => {
              const TabIcon = tab.icon;
              const isSelected = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-semibold border transition-all duration-300 ${
                    isSelected
                      ? 'bg-primary text-white border-primary shadow-lg shadow-primary/20 scale-105'
                      : 'bg-white/5 text-white/60 border-white/5 hover:bg-white/10 hover:text-white'
                  }`}
                >
                  {TabIcon && <TabIcon size={14} />}
                  {tab.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Content Area */}
        <div className="flex-1 overflow-y-auto p-6 scrollbar-thin scrollbar-thumb-white/10">
          {loading ? (
            <div className="w-full h-full flex items-center justify-center">
              <Spinner size="lg" color="primary" />
            </div>
          ) : filteredItems.length === 0 ? (
            <div className="w-full h-full flex flex-col items-center justify-center text-white/30 gap-2">
              <span className="text-4xl">🔍</span>
              <p className="text-sm font-medium">No se encontraron resultados para tu búsqueda</p>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
              {filteredItems.map((item) => {
                const coverImage = item.posterUrl || item.logoUrl || item.backdropUrl;
                return (
                  <div
                    key={`${item.type}-${item.id}`}
                    onClick={() => handleItemClick(item)}
                    className="group relative aspect-[3/4] bg-neutral-950 rounded-xl overflow-hidden border border-white/5 hover:border-primary/50 cursor-pointer transition-all duration-300 hover:scale-[1.03] shadow-md hover:shadow-primary/10"
                  >
                    {/* Image */}
                    {coverImage ? (
                      <img
                        src={coverImage}
                        alt={item.name || item.title}
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                        loading="lazy"
                      />
                    ) : (
                      <div className="w-full h-full flex flex-col items-center justify-center bg-neutral-900 text-white/20 p-4 text-center">
                        <span className="text-2xl mb-1">🎬</span>
                        <span className="text-[10px] font-bold uppercase truncate max-w-full">
                          {item.name || item.title}
                        </span>
                      </div>
                    )}

                    {/* Gradient Overlay */}
                    <div className="absolute inset-0 bg-gradient-to-t from-black via-black/40 to-transparent opacity-80 group-hover:opacity-90 transition-opacity" />

                    {/* Content Info */}
                    <div className="absolute bottom-0 left-0 right-0 p-3 space-y-1">
                      <div className="flex items-center gap-1.5">
                        <Badge
                          variant={
                            item.type === 'tv'
                              ? 'success'
                              : item.type === 'movie'
                              ? 'primary'
                              : 'accent'
                          }
                          size="sm"
                          className="text-[9px] px-1.5 py-0.5"
                        >
                          {item.type === 'tv'
                            ? 'EN VIVO'
                            : item.type === 'movie'
                            ? 'PELÍCULA'
                            : 'SERIE'}
                        </Badge>
                      </div>
                      <h4 className="text-xs font-bold text-white line-clamp-2 leading-tight">
                        {item.name || item.title}
                      </h4>
                    </div>

                    {/* Hover Add Overlay */}
                    <div className="absolute inset-0 bg-primary/20 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                      <span className="bg-primary text-white text-xs font-bold px-3 py-1.5 rounded-full shadow-lg border border-primary-light">
                        + Añadir
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
