import { assetUrl } from "@/lib/asset";
import { trpc } from "@/lib/trpc";
import { Skeleton } from "@/components/ui/skeleton";
import { usePlayer } from "@/contexts/PlayerContext";
import { faixaToPlayable } from "@shared/playable";
import { Link } from "wouter";

export default function HomeMusica() {
  const { data: topFaixas, isLoading: isLoadingMusica } = trpc.musica.getTopFaixas.useQuery();
  const { data: artistasMusica, isLoading: isLoadingArtistas } = trpc.musica.getArtistas.useQuery({
    page: 1,
    limit: 12,
  });
  const { data: albunsMusica, isLoading: isLoadingAlbuns } = trpc.musica.getAlbuns.useQuery({
    page: 1,
    limit: 8,
  });
  const { play, togglePlayPause, currentItem, isPlaying } = usePlayer();

  return (
    <div className="px-6 lg:px-10 pt-8 pb-32">
      {/* Hero */}
      <div className="mb-14">
        <h2 className="text-3xl lg:text-4xl font-bold font-ui text-white mb-3 tracking-tight">
          SpotOnFide Música
        </h2>
        <p className="text-sm lg:text-base text-white/55 font-ui max-w-2xl leading-relaxed">
          Louvor, adoração e a linha cristã, num só lugar.
        </p>
      </div>

      <div className="space-y-16">
        {/* Faixas em destaque */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold font-ui text-white tracking-wide uppercase">Faixas em destaque</h3>
            <Link href="/explorar" className="text-sof-gold hover:text-sof-gold-light text-sm font-medium transition-colors">
              Ver tudo
            </Link>
          </div>

          <div className="flex gap-5 overflow-x-auto pb-6 scrollbar-hide">
            {isLoadingMusica
              ? Array(5)
                  .fill(0)
                  .map((_, i) => (
                    <div key={i} className="flex-shrink-0 w-40 space-y-3">
                      <Skeleton className="aspect-square rounded-xl bg-sof-surface" />
                      <Skeleton className="h-4 w-3/4 bg-sof-surface" />
                    </div>
                  ))
              : topFaixas && topFaixas.length > 0
                ? topFaixas.map(fx => {
                    const isCurrentFaixa = currentItem?.kind === "musica" && currentItem.sourceId === fx.id;
                    return (
                      <div key={fx.id} className="flex-shrink-0 w-40 group cursor-pointer">
                        <div className="relative aspect-square mb-3 overflow-hidden rounded-xl bg-white/[0.05]">
                          <Link href={`/musica/faixa/${fx.id}`}>
                            <img
                              src={assetUrl(fx.capa) ?? assetUrl("/placeholder-podcast.svg")}
                              alt={fx.titulo}
                              className="object-cover w-full h-full transition-transform duration-500 group-hover:scale-105"
                            />
                          </Link>
                          <div className="absolute inset-0 bg-black/40 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity" />
                          <button
                            onClick={() => {
                              if (isCurrentFaixa) {
                                togglePlayPause();
                              } else {
                                play(
                                  faixaToPlayable(fx),
                                  topFaixas.map(t => faixaToPlayable(t)),
                                  topFaixas.findIndex(t => t.id === fx.id)
                                );
                              }
                            }}
                            className="absolute bottom-3 right-3 w-11 h-11 rounded-full bg-sof-gold text-sof-borgonha text-lg flex items-center justify-center shadow-2xl opacity-100 translate-y-0 sm:opacity-0 sm:translate-y-3 sm:group-hover:opacity-100 sm:group-hover:translate-y-0 transition-all duration-300"
                          >
                            {isCurrentFaixa && isPlaying ? "⏸" : "▶"}
                          </button>
                        </div>
                        <Link href={`/musica/faixa/${fx.id}`}>
                          <h4 className="font-ui font-semibold text-white text-sm truncate hover:text-sof-gold transition-colors">
                            {fx.titulo}
                          </h4>
                        </Link>
                      </div>
                    );
                  })
                : <p className="text-white/45 text-sm">Nenhuma faixa publicada ainda.</p>}
          </div>
        </section>

        {/* Artistas */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold font-ui text-white uppercase tracking-wide">Artistas</h3>
            <Link href="/musica/artistas" className="text-sof-gold hover:text-sof-gold-light text-sm font-medium transition-colors">
              Ver tudo
            </Link>
          </div>

          <div className="flex gap-6 overflow-x-auto pb-6 scrollbar-hide">
            {isLoadingArtistas
              ? Array(6)
                  .fill(0)
                  .map((_, i) => (
                    <div key={i} className="flex-shrink-0 w-28 space-y-3">
                      <Skeleton className="w-24 h-24 rounded-full bg-sof-surface mx-auto" />
                      <Skeleton className="h-4 w-full bg-sof-surface" />
                    </div>
                  ))
              : artistasMusica && artistasMusica.artistas.length > 0
                ? artistasMusica.artistas.map(a => (
                    <Link key={a.id} href={`/musica/artista/${a.id}`}>
                      <div className="flex-shrink-0 w-32 text-center group cursor-pointer">
                        <div className="relative w-24 h-24 mx-auto mb-4 overflow-hidden rounded-full border border-white/10 group-hover:border-sof-gold transition-all">
                          <img
                            src={assetUrl(a.foto) ?? assetUrl("/placeholder-user.svg")}
                            alt={a.nome}
                            className="object-cover w-full h-full grayscale group-hover:grayscale-0 transition-all duration-500"
                          />
                        </div>
                        <p className="text-sm font-medium font-ui text-white truncate group-hover:text-sof-gold transition-colors">
                          {a.nome}
                        </p>
                      </div>
                    </Link>
                  ))
                : <p className="text-white/45 text-sm">Nenhum artista cadastrado ainda.</p>}
          </div>
        </section>

        {/* Álbuns */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold font-ui text-white uppercase tracking-wide">Álbuns</h3>
            <Link href="/musica/albuns" className="text-sof-gold hover:text-sof-gold-light text-sm font-medium transition-colors">
              Ver tudo
            </Link>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5">
            {isLoadingAlbuns
              ? Array(4)
                  .fill(0)
                  .map((_, i) => <Skeleton key={i} className="h-56 rounded-2xl bg-sof-surface" />)
              : albunsMusica && albunsMusica.albuns.length > 0
                ? albunsMusica.albuns.map(al => (
                    <Link key={al.id} href={`/musica/album/${al.id}`}>
                      <div className="relative h-56 rounded-2xl overflow-hidden group cursor-pointer bg-white/[0.05]">
                        <img
                          src={assetUrl(al.capa) ?? assetUrl("/placeholder-series.svg")}
                          alt={al.titulo}
                          className="absolute inset-0 object-cover w-full h-full transition-transform duration-700 group-hover:scale-105"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/30 to-transparent" />
                        <div className="absolute bottom-0 left-0 p-5 w-full">
                          <span className="text-[11px] uppercase tracking-[0.2em] text-white/55 font-semibold font-ui mb-1 block">
                            {al.genero || "Música"} {al.anoLancamento ? `· ${al.anoLancamento}` : ""}
                          </span>
                          <h4 className="text-lg font-semibold font-ui text-white leading-tight group-hover:text-sof-gold transition-colors">
                            {al.titulo}
                          </h4>
                        </div>
                      </div>
                    </Link>
                  ))
                : <p className="text-white/45 text-sm">Nenhum álbum cadastrado ainda.</p>}
          </div>
        </section>
      </div>
    </div>
  );
}
