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

export default function MusicaFaixa() {
  const [, params] = useRoute("/musica/faixa/:id");
  const id = params?.id ? parseInt(params.id) : 0;

  const { data, isLoading } = trpc.musica.getFaixa.useQuery({ id }, { enabled: !!id });
  const { play, togglePlayPause, currentItem, isPlaying } = usePlayer();

  if (isLoading) {
    return (
      <div className="animate-pulse">
        <div className="flex gap-8 mb-12">
          <Skeleton className="w-64 h-64 rounded-xl bg-sof-surface" />
          <div className="flex-1 space-y-4 pt-8">
            <Skeleton className="h-4 w-24 bg-sof-surface" />
            <Skeleton className="h-12 w-3/4 bg-sof-surface" />
          </div>
        </div>
      </div>
    );
  }

  if (!data?.faixa) {
    return (
      <div>
        <p className="text-sof-text-2">Faixa não encontrada.</p>
      </div>
    );
  }

  const { faixa, artista, album, relacionadas } = data;
  const isCurrent = currentItem?.kind === "musica" && currentItem.sourceId === faixa.id;

  const handlePlay = () => {
    if (isCurrent) {
      togglePlayPause();
    } else {
      play(faixaToPlayable(faixa, { artistaNome: artista?.nome ?? null }));
    }
  };

  return (
    <div className="pb-32">
      {/* Header */}
      <div className="flex flex-col md:flex-row gap-8 mb-12">
        <div className="w-64 h-64 flex-shrink-0 shadow-2xl rounded-xl overflow-hidden border border-sof-border">
          <img
            src={assetUrl(faixa.capa || album?.capa) ?? assetUrl("/placeholder-podcast.svg")}
            alt={faixa.titulo}
            className="w-full h-full object-cover"
          />
        </div>
        <div className="flex flex-col justify-end py-2">
          {album && (
            <Link href={`/musica/album/${album.id}`}>
              <span className="text-sof-gold font-bold uppercase tracking-widest text-xs mb-2 hover:underline w-fit">
                {album.titulo}
              </span>
            </Link>
          )}
          <h1 className="text-5xl font-bold font-display text-sof-text mb-2 mt-2">{faixa.titulo}</h1>
          {artista && (
            <Link href={`/musica/artista/${artista.id}`}>
              <p className="text-sof-text-2 text-lg hover:text-sof-gold transition-colors cursor-pointer mb-6 w-fit">
                {artista.nome}
              </p>
            </Link>
          )}

          <button
            onClick={handlePlay}
            className="bg-sof-gold text-sof-borgonha hover:bg-sof-gold-light rounded-full px-8 h-12 font-bold text-lg w-fit"
          >
            {isCurrent && isPlaying ? "⏸ Pausar" : "▶ Ouvir Agora"}
          </button>
        </div>
      </div>

      {faixa.letra && (
        <div className="mb-12 max-w-2xl">
          <h2 className="text-2xl font-bold font-display text-sof-text mb-4">Letra</h2>
          <p className="text-sof-text-2 whitespace-pre-line leading-relaxed">{faixa.letra}</p>
        </div>
      )}

      {relacionadas.length > 0 && (
        <div>
          <h2 className="text-2xl font-bold font-display text-sof-text mb-6">
            {album ? "Mais deste álbum" : "Mais deste artista"}
          </h2>
          <div className="bg-sof-surface/30 rounded-2xl border border-sof-border overflow-hidden divide-y divide-sof-border/50">
            {relacionadas.map((fx, idx) => (
              <FaixaRow
                key={fx.id}
                faixa={fx}
                index={idx}
                queue={relacionadas}
                queueIndex={idx}
                fallbackCapa={faixa.capa}
                artistaNome={artista?.nome}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}