import { MessageFlags, ActionRowBuilder, StringSelectMenuBuilder } from "discord.js"
import type { ButtonInteraction } from "discord.js"
import { twitchClient } from "@/utils/twitch"
import type { GuildTwitch } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"
import { logConsoleError } from "@/utils/console"

export const id = "twitch_streamer_remove"
export async function execute(interaction: ButtonInteraction) {
	const guildProfile = await dbGuild.findOne({ guildId: interaction.guild?.id })
	if (!guildProfile) return interaction.reply({ content: t(interaction.locale, "common.database_not_found"), flags: MessageFlags.Ephemeral })

	const dbData = guildProfile.get("guildTwitch") as GuildTwitch
	if (!dbData.enabled) return interaction.reply({ content: t(interaction.locale, "twitch.module_disabled"), flags: MessageFlags.Ephemeral })
	if (!dbData.streamers.length) return interaction.reply({ content: t(interaction.locale, "twitch.no_streamers_list"), flags: MessageFlags.Ephemeral })

	// Créer la liste des streamers dans un menu de sélection
	const options = await Promise.all(dbData.streamers.map(async (streamer) => {
		try {
			const user = await twitchClient.users.getUserById(streamer.twitchUserId)
			return {
				label: user ? user.displayName : `ID: ${streamer.twitchUserId}`,
				value: streamer.twitchUserId,
				description: user ? `@${user.name}` : t(interaction.locale, "twitch.user_not_found")
			}
		} catch (error) {
			logConsoleError('twitch', 'user_fetch_error', { id: streamer.twitchUserId }, error as Error)
			return {
				label: `ID: ${streamer.twitchUserId}`,
				value: streamer.twitchUserId,
				description: t(interaction.locale, "twitch.fetch_error")
			}
		}
	}))

	const selectMenu = new StringSelectMenuBuilder()
		.setCustomId("twitch_streamer_remove")
		.setPlaceholder(t(interaction.locale, "twitch.select_streamer_to_remove"))
		.addOptions(options.slice(0, 25)) // Discord limite à 25 options

	const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu)

	return interaction.reply({ content: t(interaction.locale, "twitch.select_streamer_prompt"), components: [row], flags: MessageFlags.Ephemeral })
}
