import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useAuth } from "@/_core/hooks/useAuth";
import { BASE_PATH } from "@/const";
import { trpc } from "@/lib/trpc";
import { useLocation } from "wouter";
import { toast } from "sonner";
import { useState } from "react";

/**
 * AddToPlaylistMenuMusica — espelha AddToPlaylistMenu.tsx (Podcast).
 *
 * O container de playlist (user_playlists) é compartilhado — por isso usa
 * trpc.podcast.playlists.listar/criar, os mesmos do Podcast. Só a operação
 * de adicionar o ITEM é específica de Música (musica.playlists.adicionarFaixa),
 * porque os itens ficam em user_playlist_items_musica (ADR-003).
 *
 * REVISÃO (jul/2026, correção mobile): mesma troca de DropdownMenu por
 * Dialog centralizado feita em AddToPlaylistMenu.tsx — ver comentário lá
 * para o motivo.
 */
export default function AddToPlaylistMenuMusica({
  faixaId,
  titulo,
  className = "",
}: {
  faixaId: number;
  titulo?: string;
  className?: string;
}) {
  const { user } = useAuth();
  const [, navigate] = useLocation();
  const utils = trpc.useUtils();
  const [open, setOpen] = useState(false);

  const playlistsQuery = trpc.podcast.playlists.listar.useQuery(undefined, {
    enabled: !!user && open,
  });

  const addMutation = trpc.musica.playlists.adicionarFaixa.useMutation({
    onSuccess: () => {
      toast.success("Faixa adicionada à playlist.");
      utils.podcast.playlists.listar.invalidate();
      utils.podcast.playlists.obter.invalidate();
      setOpen(false);
    },
    onError: error => toast.error(error.message),
  });

  const criarMutation = trpc.podcast.playlists.criar.useMutation({
    onSuccess: result => {
      addMutation.mutate({ playlistId: result.id, faixaId });
    },
    onError: error => toast.error(error.message),
  });

  const handleTriggerClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!user) {
      navigate("/entrar");
      return;
    }
    setOpen(true);
  };

  const handleNovaPlaylist = () => {
    const nome = window.prompt("Nome da nova playlist:");
    if (!nome?.trim()) return;
    criarMutation.mutate({ titulo: nome.trim() });
  };

  const shareUrl = `${window.location.origin}${BASE_PATH}/share/faixa/${faixaId}`;

  const handleWhatsApp = () => {
    const texto = encodeURIComponent(
      titulo ? `Ouça "${titulo}" no SpotOnFide: ${shareUrl}` : `Ouça no SpotOnFide: ${shareUrl}`
    );
    window.open(`https://wa.me/?text=${texto}`, "_blank", "noopener,noreferrer");
    setOpen(false);
  };

  const handleCopiarLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      toast.success("Link copiado.");
    } catch {
      toast.error("Não foi possível copiar o link.");
    }
    setOpen(false);
  };

  return (
    <>
      <button
        type="button"
        onClick={handleTriggerClick}
        title="Mais opções"
        aria-label="Mais opções"
        className={`w-10 h-10 flex items-center justify-center text-xl text-sof-text-3 hover:text-sof-gold transition-colors flex-shrink-0 ${className}`}
      >
        ⋮
      </button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-sm bg-sof-borgonha-light border-sof-border text-sof-text">
          <DialogHeader>
            <DialogTitle className="text-sof-text truncate pr-6">
              {titulo ?? "Opções"}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-1">
            <p className="text-xs font-bold uppercase tracking-widest text-sof-text-3 px-1 pt-1">
              Adicionar à playlist
            </p>
            <div className="max-h-48 overflow-y-auto">
              {playlistsQuery.data?.length ? (
                playlistsQuery.data.map(pl => (
                  <button
                    key={pl.id}
                    onClick={() => addMutation.mutate({ playlistId: pl.id, faixaId })}
                    className="w-full text-left px-3 py-3 rounded-lg hover:bg-sof-surface active:bg-sof-surface transition-colors truncate text-base"
                  >
                    {pl.titulo}
                  </button>
                ))
              ) : (
                <p className="px-3 py-3 text-sof-text-3 text-sm">Você ainda não tem playlists</p>
              )}
            </div>
            <button
              onClick={handleNovaPlaylist}
              className="w-full text-left px-3 py-3 rounded-lg hover:bg-sof-surface active:bg-sof-surface transition-colors text-sof-gold font-medium text-base"
            >
              + Nova playlist
            </button>

            <div className="border-t border-sof-border my-2" />

            <p className="text-xs font-bold uppercase tracking-widest text-sof-text-3 px-1">
              Compartilhar
            </p>
            <button
              onClick={handleWhatsApp}
              className="w-full text-left px-3 py-3 rounded-lg hover:bg-sof-surface active:bg-sof-surface transition-colors text-base"
            >
              WhatsApp
            </button>
            <button
              onClick={handleCopiarLink}
              className="w-full text-left px-3 py-3 rounded-lg hover:bg-sof-surface active:bg-sof-surface transition-colors text-base"
            >
              Copiar link
            </button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
