/**
 * Buscar — Página dedicada de busca
 *
 * Mobile: aba da BottomNav "Buscar"
 * Desktop: complementa a busca do Topbar com resultados mais ricos
 *
 * HUB-INTEGRATION-POINT (Fase 6):
 * Quando a busca global do HUB existir, adicionar aqui os resultados
 * de Instituto, Biblioteca e Comunidade sem alterar a estrutura.
 */

import MainLayout from "@/components/MainLayout";
import EpisodioRow from "@/components/EpisodioRow";
import { Skeleton } from "@/components/ui/skeleton";
import { trpc } from "@/lib/trpc";
import { assetUrl } from "@/lib/asset";
import { Link } from "wouter";
import { useState } from "react";

export default function Buscar() {
  const [query, setQuery] = useState("");
  const [debouncedQuery, setDebouncedQuery] = useState("");

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setQuery(val);
    clearTimeout((window as any)._buscarTimeout);
    (window as any)._buscarTimeout = setTimeout(() => {
      setDebouncedQuery(val.trim());
    }, 300);
  };

  const { data, isLoading } = trpc.podcast.buscar.useQuery(
    { query: debouncedQuery },
    { enabled: debouncedQuery.length > 1 }
  );

  const hasResults =
    !!data &&
    (data.episodios.length > 0 ||
      data.apresentadores.length > 0 ||
      data.programas.length > 0);

  return (
    <MainLayout>
      <div className="min-h-full" style={{ background: "linear-gradient(180deg, #3d0a1e 0%, #2a0110 20%, #0a0005 100%)" }}>
        <div className="px-4 lg:px-8 py-6">

          {/* Campo de busca */}
          <div className="relative mb-8">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth={2}
              className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40 pointer-events-none"
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 15.803 7.5 7.5 0 0015.803 15.803z" />
            </svg>
            <input
              type="text"
              autoFocus
              placeholder="Buscar episódios, séries, apresentadores..."
              value={query}
              onChange={handleChange}
              className="w-full pl-12 pr-4 py-3.5 rounded-2xl text-white placeholder-white/30 text-base focus:outline-none focus:ring-2 focus:ring-sof-gold/40"
              style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.12)" }}
            />
          </div>

          {/* Estado vazio */}
          {!debouncedQuery && (
            <div className="text-center py-16">
              <div className="text-5xl mb-4">🔍</div>
              <p className="text-white/40 font-ui text-base">
                Digite para buscar episódios, séries ou apresentadores
              </p>
            </div>
          )}

          {/* Loading */}
          {isLoading && debouncedQuery.length > 1 && (
            <div className="space-y-3">
              {Array(5).fill(0).map((_, i) => (
                <Skeleton key={i} className="h-16 rounded-xl bg-white/5" />
              ))}
            </div>
          )}

          {/* Sem resultados */}
          {!isLoading && debouncedQuery.length > 1 && !hasResults && (
            <div className="text-center py-16">
              <p className="text-white/40 font-ui">
                Nenhum resultado para "
                <span className="text-white/70">{debouncedQuery}</span>"
              </p>
            </div>
          )}

          {/* Resultados */}
          {hasResults && (
            <div className="space-y-8">

              {/* Episódios */}
              {data.episodios.length > 0 && (
                <section>
                  <h2 className="text-xs font-bold font-ui uppercase tracking-widest text-white/40 mb-3 px-1">
                    Episódios
                  </h2>
                  <div
                    className="rounded-2xl overflow-hidden"
                    style={{ background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)" }}
                  >
                    {data.episodios.map((ep, idx) => (
                      <EpisodioRow
                        key={ep.id}
                        episodio={ep}
                        index={idx}
                        queue={data.episodios}
                        queueIndex={idx}
                      />
                    ))}
                  </div>
                </section>
              )}

              {/* Séries */}
              {data.programas.length > 0 && (
                <section>
                  <h2 className="text-xs font-bold font-ui uppercase tracking-widest text-white/40 mb-3 px-1">
                    Séries
                  </h2>
                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    {data.programas.map(prog => (
                      <Link key={prog.id} href={`/serie/${prog.id}?autoplay=true`}>
                        <div
                          className="group rounded-xl overflow-hidden cursor-pointer"
                          style={{ background: "rgba(255,255,255,0.05)" }}
                        >
                          <div className="relative aspect-square">
                            <img
                              src={assetUrl(prog.capa) ?? assetUrl("/placeholder-series.svg")}
                              alt={prog.titulo}
                              className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
                          </div>
                          <div className="p-3">
                            <p className="text-sm font-semibold font-ui text-white truncate group-hover:text-sof-gold transition-colors">
                              {prog.titulo}
                            </p>
                            <p className="text-xs text-white/40 truncate">{prog.categoria}</p>
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </section>
              )}

              {/* Apresentadores */}
              {data.apresentadores.length > 0 && (
                <section>
                  <h2 className="text-xs font-bold font-ui uppercase tracking-widest text-white/40 mb-3 px-1">
                    Apresentadores
                  </h2>
                  <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide">
                    {data.apresentadores.map(ap => (
                      <Link key={ap.id} href={`/apresentador/${ap.id}`}>
                        <div className="flex-shrink-0 w-24 text-center group cursor-pointer">
                          <div className="w-20 h-20 mx-auto mb-2 rounded-full overflow-hidden border-2 border-white/10 group-hover:border-sof-gold transition-colors">
                            <img
                              src={assetUrl(ap.foto) ?? assetUrl("/placeholder-user.svg")}
                              alt={ap.nome}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <p className="text-xs font-ui text-white/70 truncate group-hover:text-sof-gold transition-colors">
                            {ap.nome}
                          </p>
                        </div>
                      </Link>
                    ))}
                  </div>
                </section>
              )}

            </div>
          )}
        </div>
      </div>
    </MainLayout>
  );
}
