import disnake
from disnake.ext import commands
from utils.premium import check_premium_tier


OWNER_ID = 971446412690722826


def is_authorized(interaction: disnake.ApplicationCommandInteraction) -> bool:
    return interaction.user.id == OWNER_ID


class AnnouncementModal(disnake.ui.Modal):
    def __init__(self, cog: "SentBotMessages"):
        self.cog = cog
        components = [
            disnake.ui.TextInput(
                label="Titre principal de l'annonce",
                placeholder="Ex: Mise à jour important / Maintenance / Nouveau système",
                custom_id="announcement_title",
                required=True,
                max_length=100,
            ),
            disnake.ui.TextInput(
                label="Message de l'annonce (contenu réel)",
                style=disnake.TextInputStyle.paragraph,
                placeholder="Écris le vrai contenu de l'annonce ici.",
                custom_id="announcement_message",
                required=True,
                max_length=4000,
            ),
            disnake.ui.TextInput(
                label="Message de prévention / contexte MP",
                style=disnake.TextInputStyle.paragraph,
                placeholder="Ex: Ce MP vous informe d'une annonce importante.",
                custom_id="announcement_prevention",
                required=True,
                max_length=1000,
            ),
        ]
        super().__init__(
            title="Annonce aux propriétaires",
            custom_id="announcement_modal",
            components=components,
        )

    async def callback(self, interaction: disnake.ModalInteraction):
        title = (interaction.text_values.get("announcement_title") or "").strip()
        message = (interaction.text_values.get("announcement_message") or "").strip()
        prevention = (interaction.text_values.get("announcement_prevention") or "").strip()

        await interaction.response.defer(ephemeral=True)

        preview_container = disnake.ui.Container(
            disnake.ui.TextDisplay(content=f"# {title}"),
            disnake.ui.Separator(divider=True),
            disnake.ui.TextDisplay(content=prevention),
            disnake.ui.Separator(divider=True),
            disnake.ui.TextDisplay(content=message),
            disnake.ui.Separator(divider=True),
            disnake.ui.TextDisplay(
                content=(
                    "📍 **Prévisualisation**\n"
                    "Le même format sera envoyé aux propriétaires."
                )
            )
        )

        successful = 0
        failed_servers = []

        for guild in self.cog.bot.guilds:
            try:
                owner = guild.owner
                if owner is None:
                    owner = await guild.fetch_member(guild.owner_id)

                container = disnake.ui.Container(
                    disnake.ui.TextDisplay(content=f"# {title}"),
                    disnake.ui.Separator(divider=True),
                    disnake.ui.TextDisplay(content=prevention),
                    disnake.ui.Separator(divider=True),
                    disnake.ui.TextDisplay(content=message),
                    disnake.ui.Separator(divider=True),
                    disnake.ui.TextDisplay(
                        content=(
                            f"📍 **Serveur** : {guild.name}\n"
                            f"🆔 **ID** : `{guild.id}`"
                        )
                    )
                )

                await owner.send(components=[container])
                successful += 1
            except Exception as e:
                failed_servers.append(f"{guild.name} ({guild.id}) : {e}")

        result_text = (
            f"✅ Annonce envoyée à {successful} propriétaire(s)."
            if not failed_servers
            else (
                f"✅ Annonce envoyée à {successful} propriétaire(s).\n"
                f"❌ Échecs ({len(failed_servers)}):\n"
                f"- {'\n- '.join(failed_servers[:10])}"
                f"{'\n... et ' + str(len(failed_servers) - 10) + ' autres' if len(failed_servers) > 10 else ''}"
            )
        )

        result_container = disnake.ui.Container(
            disnake.ui.TextDisplay(content=result_text),
            disnake.ui.Separator(divider=True),
            disnake.ui.TextDisplay(content="🧩 Aperçu du format envoyé aux propriétaires :"),
            disnake.ui.Separator(divider=True),
            *preview_container.children
        )

        await interaction.edit_original_response(components=[result_container])


class SentBotMessages(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(
        name="sentbotmessages",
        description="Le bot envoie un message dans un salon choisi."
    )
    @check_premium_tier()
    async def sentbotmessages(
        self,
        interaction: disnake.ApplicationCommandInteraction,
        message: str = commands.Param(description="Le message à envoyer"),
        salon: disnake.TextChannel = commands.Param(description="Le salon où envoyer le message")
    ):
        # Vérifie si l'utilisateur est admin
        if not interaction.user.guild_permissions.administrator:
            await interaction.response.send_message(
                "⛔ Tu n'as pas la permission d'utiliser cette commande.",
                ephemeral=True
            )
            return

        try:
            await salon.send(message)
            await interaction.response.send_message(
                f"✅ Message envoyé dans {salon.mention}.",
                ephemeral=True
            )
        except Exception as e:
            await interaction.response.send_message(
                f"❌ Une erreur est survenue : {e}",
                ephemeral=True
            )

    @commands.slash_command(
        name="annonce_proprietaires",
        description="Ouvrir le formulaire d'annonce pour les propriétaires."
    )
    @check_premium_tier()
    @commands.check(is_authorized)
    async def annonce_proprietaires(
        self,
        interaction: disnake.ApplicationCommandInteraction,
    ):
        await interaction.response.send_modal(AnnouncementModal(self))


def setup(bot):
    bot.add_cog(SentBotMessages(bot))

