import { EmbedBuilder, MessageFlags } from "discord.js"
import type { ButtonInteraction } from "discord.js"
import crypto from "crypto"
import * as Freebox from "@/utils/freebox"
import type { APIResponseData, APIResponseDataError, GetChallenge, LcdConfig, OpenSession } from "@/types/freebox"
import type { GuildFbx } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"
import { logConsoleError } from "@/utils/console"

export const id = "freebox_lcd_status"
export async function execute(interaction: ButtonInteraction) {
	await interaction.deferReply({ flags: MessageFlags.Ephemeral })

	const guildProfile = await dbGuild.findOne({ guildId: interaction.guild?.id })
	if (!guildProfile) return interaction.followUp({ content: t(interaction.locale, "common.database_not_found"), flags: MessageFlags.Ephemeral })

	const dbData = guildProfile.get("guildFbx") as GuildFbx
	if (!dbData.enabled || !dbData.host || !dbData.appToken) {
		return interaction.followUp({ content: t(interaction.locale, "freebox.general.incomplete_configuration"), flags: MessageFlags.Ephemeral })
	}

	try {
		// Connexion à l'API Freebox
		const challengeData = await Freebox.Login.Challenge(dbData.host) as APIResponseData<GetChallenge>
		if (!challengeData.success) return await Freebox.handleError(challengeData as APIResponseDataError, interaction, false)

		const password = crypto.createHmac("sha1", dbData.appToken).update(challengeData.result.challenge).digest("hex")
		const sessionData = await Freebox.Login.Session(dbData.host, password) as APIResponseData<OpenSession>
		if (!sessionData.success) return await Freebox.handleError(sessionData as APIResponseDataError, interaction, false)

		const sessionToken = sessionData.result.session_token
		if (!sessionToken) return await interaction.followUp({ content: t(interaction.locale, "freebox.auth.session_token_failed"), flags: MessageFlags.Ephemeral })

		// Récupération de la configuration LCD
		const lcdData = await Freebox.Get.LcdConfig(dbData.host, sessionToken) as APIResponseData<LcdConfig>
		if (!lcdData.success) return await Freebox.handleError(lcdData as APIResponseDataError, interaction, false)

		const lcdConfig = lcdData.result
		
		// Création de l'embed avec les informations LCD
		const embed = new EmbedBuilder()
			.setTitle(t(interaction.locale, "freebox.lcd.config_title"))
			.setColor(lcdConfig.led_strip_enabled ? 0x00ff00 : 0xff0000)
			.addFields(
				{
					name: t(interaction.locale, "freebox.lcd.led_strip"),
					value: lcdConfig.led_strip_enabled ? t(interaction.locale, "freebox.lcd.led_strip_on") : t(interaction.locale, "freebox.lcd.led_strip_off"),
					inline: true
				},
				{
					name: t(interaction.locale, "freebox.lcd.brightness"),
					value: `${lcdConfig.brightness}%`,
					inline: true
				},
				{
					name: t(interaction.locale, "freebox.lcd.orientation"),
					value: lcdConfig.orientation === 0 ? t(interaction.locale, "freebox.lcd.orientation_portrait") : t(interaction.locale, "freebox.lcd.orientation_landscape"),
					inline: true
				}
			)

		// Informations du timer si configuré
		if (dbData.lcd) {
			const timerStatus = dbData.lcd.enabled ? t(interaction.locale, "freebox.status.timer_enabled") : t(interaction.locale, "freebox.status.timer_disabled")
			const botManaged = dbData.lcd.botId ? `<@${dbData.lcd.botId}>` : t(interaction.locale, "freebox.status.timer_no_manager")
			const morningTime = dbData.lcd.morningTime ?? t(interaction.locale, "freebox.status.timer_not_configured")
			const nightTime = dbData.lcd.nightTime ?? t(interaction.locale, "freebox.status.timer_not_configured")
			
			embed.addFields({
				name: t(interaction.locale, "freebox.lcd.timer_auto"),
				value: [
					t(interaction.locale, "freebox.timer.status_field", { status: timerStatus }),
					t(interaction.locale, "freebox.timer.managed_by", { manager: botManaged }),
					t(interaction.locale, "freebox.timer.morning", { time: morningTime }),
					t(interaction.locale, "freebox.timer.night", { time: nightTime })
				].join('\n'),
				inline: false
			})
		}

		embed.setTimestamp()

		return await interaction.followUp({ embeds: [embed], flags: MessageFlags.Ephemeral })
	} catch (error) {
		logConsoleError('freebox', 'lcd_status_error', undefined, error as Error)
		return interaction.followUp({ content: t(interaction.locale, "freebox.lcd.unexpected_error"), flags: MessageFlags.Ephemeral })
	}
}
