'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { FiSearch } from 'react-icons/fi';
import CategoryTabs from '@/components/content/CategoryTabs';
import ContentGrid from '@/components/content/ContentGrid';
import { searchApi } from '@/lib/api';
import type { Channel, Movie, Series, SearchFilter } from '@/types';
import Spinner from '@/components/ui/Spinner';

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

export default function SearchPage() {
  const [query, setQuery] = useState('');
  const [filter, setFilter] = useState<SearchFilter>('all');
  const [results, setResults] = useState<{ channels: Channel[]; movies: Movie[]; series: Series[] }>({
    channels: [],
    movies: [],
    series: [],
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!query.trim()) {
      setResults({ channels: [], movies: [], series: [] });
      return;
    }

    setLoading(true);
    const handler = setTimeout(async () => {
      try {
        const data = await searchApi.search(query, filter);
        setResults({
          channels: data.channels || [],
          movies: data.movies || [],
          series: data.series || [],
        });
      } catch (err) {
        console.error('Error performing search:', err);
      } finally {
        setLoading(false);
      }
    }, 500); // 500ms debounce

    return () => clearTimeout(handler);
  }, [query, filter]);

  const showChannels = filter === 'all' || filter === 'channels';
  const showMovies = filter === 'all' || filter === 'movies';
  const showSeries = filter === 'all' || filter === 'series';
  
  const totalResults = (showChannels ? results.channels.length : 0) + 
                       (showMovies ? results.movies.length : 0) + 
                       (showSeries ? results.series.length : 0);

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      {/* Search input */}
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative"
      >
        <FiSearch className="absolute left-5 top-1/2 -translate-y-1/2 text-white/40" size={22} />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Buscar canales, películas, series..."
          autoFocus
          className="w-full input-search text-lg py-4 pl-14 pr-6"
        />
        {loading && (
          <div className="absolute right-5 top-1/2 -translate-y-1/2">
            <Spinner size="sm" color="primary" />
          </div>
        )}
      </motion.div>

      {/* Filter tabs */}
      <CategoryTabs
        categories={searchFilters}
        activeCategory={filter}
        onChange={(id) => setFilter(id as SearchFilter)}
      />

      {/* Results */}
      {query.trim() ? (
        <div className="space-y-8">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-20">
              <Spinner size="lg" color="primary" />
              <p className="text-white/40 text-sm mt-4">Buscando en el servidor...</p>
            </div>
          ) : (
            <>
              <p className="text-white/40 text-sm">
                {totalResults} resultado{totalResults !== 1 ? 's' : ''} para &ldquo;{query}&rdquo;
              </p>

              {showChannels && results.channels.length > 0 && (
                <div>
                  <h2 className="text-lg font-bold text-white mb-4">📺 Canales</h2>
                  <ContentGrid items={results.channels} type="channel" />
                </div>
              )}

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

              {showSeries && results.series.length > 0 && (
                <div>
                  <h2 className="text-lg font-bold text-white mb-4">📺 Series</h2>
                  <ContentGrid items={results.series} type="series" />
                </div>
              )}

              {totalResults === 0 && (
                <div className="flex flex-col items-center justify-center py-20">
                  <div className="w-20 h-20 rounded-full bg-dark-200 flex items-center justify-center mb-4">
                    <FiSearch size={32} className="text-white/20" />
                  </div>
                  <p className="text-white/50 text-lg font-medium">No se encontraron resultados</p>
                  <p className="text-white/30 text-sm mt-1">Intenta con otros términos de búsqueda</p>
                </div>
              )}
            </>
          )}
        </div>
      ) : (
        <div className="space-y-8 py-4">
          <div className="text-center py-10 max-w-sm mx-auto select-none font-sans">
            <div className="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4 mx-auto text-white/20">
              <FiSearch size={32} />
            </div>
            <p className="text-white/60 text-base font-bold">Escribe para buscar</p>
            <p className="text-white/30 text-xs mt-1">Busca canales, películas o series por nombre o género.</p>
          </div>

          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white/50 uppercase tracking-widest select-none">Búsquedas sugeridas</h3>
            <div className="flex flex-wrap gap-2.5 font-sans">
              {[
                { label: '🏆 Mundial', query: 'mundial' },
                { label: '⚽ Deportes', query: 'deportes' },
                { label: '🎬 Acción', query: 'acción' },
                { label: '🍿 Comedia', query: 'comedia' },
                { label: '🍿 Terror', query: 'terror' },
                { label: '📰 Noticias', query: 'noticias' },
                { label: '📺 HBO', query: 'hbo' },
                { label: '🎥 Estrenos', query: 'estreno' },
              ].map((sug) => (
                <button
                  key={sug.query}
                  onClick={() => setQuery(sug.query)}
                  className="px-3.5 py-2 bg-white/5 hover:bg-primary/20 hover:text-white border border-white/5 hover:border-primary/30 rounded-full text-xs font-bold text-white/60 transition-all cursor-pointer active:scale-95 flex items-center gap-1 select-none border-0"
                >
                  {sug.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
