import { SlashCommandBuilder, EmbedBuilder, MessageFlags } from "discord.js"
import type { ChatInputCommandInteraction } from "discord.js"
import { useQueue, useMainPlayer } from "discord-player"
import type { LrcSearchResult } from "discord-player"
import { t } from "@/utils/i18n"

export const data = new SlashCommandBuilder()
	.setName("lyrics")
	.setDescription("Search for song lyrics")
	.setNameLocalizations({ fr: "paroles" })
	.setDescriptionLocalizations({ fr: "Rechercher les paroles d'une musique" })
	.addStringOption(option => option
		.setName("search")
		.setDescription("Search for a specific song")
		.setNameLocalizations({ fr: "recherche" })
		.setDescriptionLocalizations({ fr: "Chercher une musique spécifique" })
	)

export async function execute(interaction: ChatInputCommandInteraction) {
	await interaction.deferReply()

	const player = useMainPlayer()
	const embed = new EmbedBuilder().setColor("#ffff64").setFooter({ text: "Powered by Genius" })
	let lyrics = [] as LrcSearchResult[]

	const query = interaction.options.getString("search", false)
	if (!query) {
		const queue = useQueue(interaction.guild?.id ?? "")
		if (!queue) return interaction.followUp({ content: t(interaction.locale, "player.no_queue"), flags: MessageFlags.Ephemeral })

		const track = queue.currentTrack
		if (!track) return interaction.followUp({ content: t(interaction.locale, "player.no_current_track"), flags: MessageFlags.Ephemeral })

		lyrics = await player.lyrics.search({ trackName: track.title, artistName: track.author })

		if (!lyrics.length) return interaction.followUp({ content: t(interaction.locale, "player.no_lyrics_found"), flags: MessageFlags.Ephemeral })
		const trimmedLyrics = lyrics[0].plainLyrics.substring(0, 1997)

		embed
			.setTitle(track.title)
			.setURL(track.url)
			.setDescription(trimmedLyrics.length === 1997 ? `${trimmedLyrics}...` : trimmedLyrics)
			.setThumbnail(track.thumbnail)
			.setAuthor({ name: track.author, url: `https://genius.com/search?q=${track.author.replace(/ /g, "-")}` })
	}
	else {
		lyrics = await player.lyrics.search({ q: query })

		if (!lyrics.length) return interaction.followUp({ content: t(interaction.locale, "player.no_lyrics_found"), flags: MessageFlags.Ephemeral })
		const trimmedLyrics = lyrics[0].plainLyrics.substring(0, 1997)

		embed
			.setTitle(lyrics[0].name)
			.setURL(`https://genius.com/search?q=${query.replace(/ /g, "%20")}`)
			.setDescription(trimmedLyrics.length === 1997 ? `${trimmedLyrics}...` : trimmedLyrics)
			.setThumbnail("https://play-lh.googleusercontent.com/e6-dZlTM-gJ2sFxFFs3X15O84HEv6jc9PQGgHtVTn7FP6lUXeEAkDl9v4RfVOwbSuQ")
			.setAuthor({ name: lyrics[0].artistName, url: `https://genius.com/search?q=${lyrics[0].artistName.replace(/ /g, "-")}` })
	}

	return interaction.followUp({ embeds: [embed] })
}
