import { SlashCommandBuilder, PermissionFlagsBits, MessageFlags, ChannelType } from "discord.js"
import type { ChatInputCommandInteraction } from "discord.js"
import { generateDiscoEmbed } from "@/utils/player"
import type { Disco } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"

export const data = new SlashCommandBuilder()
	.setName("disco")
	.setDescription("Manage the Disco module")
	.setDescriptionLocalizations({ fr: "Gérer le module Disco" })
	.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
	.addSubcommand(subcommand => subcommand
		.setName("status")
		.setDescription("Display Disco mode status")
		.setNameLocalizations({ fr: "statut" })
		.setDescriptionLocalizations({ fr: "Afficher le statut du mode Disco" })
	)
	.addSubcommand(subcommand => subcommand
		.setName("channel")
		.setDescription("Configure the channel for Disco effects")
		.setNameLocalizations({ fr: "canal" })
		.setDescriptionLocalizations({ fr: "Configurer le canal pour les effets Disco" })
		.addChannelOption(option => option
			.setName("channel")
			.setDescription("The channel where to apply Disco effects")
			.setNameLocalizations({ fr: "canal" })
			.setDescriptionLocalizations({ fr: "Le canal où appliquer les effets Disco" })
			.setRequired(true)
		)
	)

export async function execute(interaction: ChatInputCommandInteraction) {
	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("guildPlayer.disco") as Disco

	const subcommand = interaction.options.getSubcommand(true)
	if (subcommand === "status") {
		const { embed, components } = generateDiscoEmbed(dbData, interaction.client, interaction.guild?.id ?? "", interaction.locale)

		return interaction.reply({ embeds: [embed], components: components, flags: MessageFlags.Ephemeral })
	}
	else if (subcommand === "channel") {
		const channel = interaction.options.getChannel("channel", true)
		if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) return interaction.reply({
			content: t(interaction.locale, "common.invalid_channel_type"),
			flags: MessageFlags.Ephemeral
		})

		dbData.channelId = channel.id

		guildProfile.set("guildPlayer.disco", dbData)
		guildProfile.markModified("guildPlayer.disco")
		await guildProfile.save().catch(console.error)

		return interaction.reply({ content: t(interaction.locale, "player.disco.channel_configured_success", { channel: channel.name ?? "Inconnu" }), flags: MessageFlags.Ephemeral })
	}
}
