import { usePlayer } from "@/contexts/PlayerContext";
import { assetUrl } from "@/lib/asset";
import type { PodcastEpisodio } from "@shared/types";
import { episodioToPlayable } from "@shared/playable";
import { Link } from "wouter";
import FavoritoButton from "./FavoritoButton";

export default function EpisodioCard({
  episodio,
  queue,
  queueIndex,
  subtitle,
}: {
  episodio: PodcastEpisodio;
  queue?: PodcastEpisodio[];
  queueIndex?: number;
  subtitle?: string;
}) {
  const { play, togglePlayPause, currentItem, isPlaying } = usePlayer();
  const isCurrent = currentItem?.kind === "episodio" && currentItem.sourceId === episodio.id;

  const handlePlayClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (isCurrent) {
      togglePlayPause();
    } else {
      play(episodioToPlayable(episodio), queue?.map(episodioToPlayable), queueIndex);
    }
  };

  return (
    <div className="group bg-sof-surface hover:bg-sof-borgonha-light p-4 rounded-xl transition-all border border-transparent hover:border-sof-gold/20">
      <div className="relative aspect-square mb-4 overflow-hidden rounded-lg shadow-lg">
        <Link href={`/episodio/${episodio.id}`}>
          <img
            src={assetUrl(episodio.capa) ?? assetUrl("/placeholder-podcast.svg")}
            alt={episodio.titulo}
            className="object-cover w-full h-full transition-transform duration-500 group-hover:scale-110 cursor-pointer"
          />
        </Link>
        <div className="absolute inset-0 bg-black/20 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity flex items-center justify-center pointer-events-none">
          <button
            onClick={handlePlayClick}
            className="pointer-events-auto w-12 h-12 bg-sof-gold rounded-full flex items-center justify-center text-sof-borgonha text-xl shadow-xl transform translate-y-0 sm:translate-y-4 sm:group-hover:translate-y-0 transition-transform"
          >
            {isCurrent && isPlaying ? "⏸" : "▶"}
          </button>
        </div>
        <div className="absolute top-2 right-2">
          <FavoritoButton episodioId={episodio.id} className="text-lg drop-shadow" />
        </div>
      </div>
      <Link href={`/episodio/${episodio.id}`}>
        <h4 className="font-bold text-sof-text truncate mb-1 hover:text-sof-gold cursor-pointer transition-colors">
          {episodio.titulo}
        </h4>
      </Link>
      <p className="text-xs text-sof-text-3 truncate">
        {subtitle ?? (episodio.numeroEpisodio ? `Episódio ${episodio.numeroEpisodio}` : "")}
      </p>
    </div>
  );
}
