import discord
import html
import re
from botdiscord.translate import get_lang_mapping, get_flag_mapping, get_name_to_code, translate_text
from botdiscord.database import (
    get_message, 
    save_translation, 
    get_cached_translation, 
    get_active_languages, 
    get_bot_languages,
    get_available_languages,
    save_message
)
from utils.logger import discord_logger as log
from utils.cache import cache_increment

# Rate Limit: máximo 1 clic por usuario por idioma cada 3 segundos
_RATE_LIMIT_SECONDS = 3

class TranslationButton(discord.ui.Button):
    def __init__(self, lang_name: str, lang_code: str, flag: str):
        label = flag if flag else lang_name
        custom_id = f"btn_trans_{lang_code}"
        super().__init__(label=label, style=discord.ButtonStyle.primary, custom_id=custom_id)
        self.lang_code = lang_code
        self.lang_name = lang_name
        self.flag = flag

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer()
        
        # Rate Limiting: verificamos que el usuario no esté haciendo spam
        rate_key = f"rl:discord:{interaction.user.id}:{self.lang_code}"
        clicks = cache_increment(rate_key, ttl=_RATE_LIMIT_SECONDS)
        if clicks > 1:
            await interaction.followup.send(
                f"⏳ Por favor espera {_RATE_LIMIT_SECONDS} segundos entre traducciones.",
                ephemeral=True
            )
            return
        
        try:
            if not interaction.message.reference:
                await interaction.followup.send("⚠️ No se pudo encontrar el mensaje original.", ephemeral=True)
                return
                
            original_msg_id = interaction.message.reference.message_id
            db_msg = get_message(original_msg_id)
            
            if not db_msg:
                await interaction.followup.send("⚠️ Mensaje no encontrado en la base de datos.", ephemeral=True)
                return

            text = db_msg['content']
            mentions_map = db_msg['mentions_map']
            
            cached = get_cached_translation(original_msg_id, self.lang_code)
            if cached:
                translated = cached
            else:
                translated = await translate_text(text, self.lang_code)
                save_translation(original_msg_id, self.lang_code, translated)
            
            translated = html.unescape(translated)
            if mentions_map:
                for placeholder, mention in mentions_map.items():
                    translated = translated.replace(placeholder, mention)
                    translated = translated.replace(placeholder.replace(" ", ""), mention)
            
            guild_id = interaction.guild_id
            active_codes = get_active_languages(guild_id)
            if not active_codes:
                active_codes = get_bot_languages("discord")
            
            db_langs = get_available_languages()
            
            new_view = discord.ui.View(timeout=None)
            for lang in db_langs:
                if lang['code'] in active_codes:
                    new_view.add_item(TranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
            
            await interaction.edit_original_response(content=translated, view=new_view)
            
        except Exception as e:
            log.error(f"Error en botón de traducción Discord: {e}")
            await interaction.followup.send(f"❌ Error: {str(e)}", ephemeral=True)

class PersistentTranslationView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        db_langs = get_available_languages()
        for lang in db_langs:
            self.add_item(TranslationButton(lang['name'], lang['code'], lang.get('flag', '')))

class ConfigSelect(discord.ui.Select):
    def __init__(self, guild_id: int, bot_type: str = "discord"):
        lang_mapping = get_lang_mapping(bot_type)
        # get_flag_mapping ya usa la base de datos internamente, así que está bien
        flag_mapping = get_flag_mapping(bot_type)
        active = get_active_languages(guild_id)
        
        # Obtenemos banderas actualizadas de la BD para el menú de configuración
        db_langs = {l['code']: l.get('flag', '') for l in get_available_languages()}
        
        options = []
        for name, code in lang_mapping.items():
            flag = db_langs.get(code, flag_mapping.get(code, ""))
            options.append(discord.SelectOption(label=f"{flag} {name}" if flag else name, value=name, default=(code in active)))
        
        super().__init__(placeholder="Selecciona idiomas...", min_values=0, max_values=len(options), options=options)

    async def callback(self, interaction: discord.Interaction):
        from botdiscord.database import set_active_languages
        lang_mapping = get_lang_mapping("discord")
        selected_codes = [lang_mapping[val] for val in self.values]
        set_active_languages(interaction.guild_id, selected_codes)
        await interaction.response.send_message("Configuración actualizada.", ephemeral=True)

class ConfigView(discord.ui.View):
    def __init__(self, guild_id: int, bot_type: str = "discord"):
        super().__init__()
        self.add_item(ConfigSelect(guild_id, bot_type))

class WelcomeTranslationButton(discord.ui.Button):
    def __init__(self, lang_name: str, lang_code: str, flag: str):
        label = flag if flag else lang_name
        custom_id = f"btn_welcome_{lang_code}"
        super().__init__(label=label, style=discord.ButtonStyle.primary, custom_id=custom_id)
        self.lang_code = lang_code
        self.lang_name = lang_name
        self.flag = flag

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer()
        
        try:
            original_msg_id = interaction.message.id
            db_msg = get_message(original_msg_id)
            
            if not db_msg:
                await interaction.followup.send("⚠️ Mensaje no encontrado en la base de datos.", ephemeral=True)
                return

            text = db_msg['content']
            mentions_map = db_msg['mentions_map'] or {}
            
            cached = get_cached_translation(original_msg_id, self.lang_code)
            if cached:
                translated = cached
            else:
                translated = await translate_text(text, self.lang_code)
                save_translation(original_msg_id, self.lang_code, translated)
            
            translated = html.unescape(translated)
            if mentions_map:
                for placeholder, mention in mentions_map.items():
                    translated = translated.replace(placeholder, mention)
                    translated = translated.replace(placeholder.replace(" ", ""), mention)
            
            guild_id = interaction.guild_id
            active_codes = get_active_languages(guild_id)
            if not active_codes:
                active_codes = get_bot_languages("discord")
            
            db_langs = get_available_languages()
            
            new_view = discord.ui.View(timeout=None)
            for lang in db_langs:
                if lang['code'] in active_codes:
                    new_view.add_item(WelcomeTranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
            
            await interaction.edit_original_response(content=translated, view=new_view)
            
        except Exception as e:
            import traceback
            print(f"[ERROR Welcome UI] {e}")
            traceback.print_exc()
            await interaction.followup.send(f"❌ Error: {str(e)}", ephemeral=True)

class WelcomeTranslationView(discord.ui.View):
    def __init__(self, guild_id: int = None):
        super().__init__(timeout=None)
        db_langs = get_available_languages()
        
        if guild_id is not None:
            active_codes = get_active_languages(guild_id)
            if not active_codes:
                active_codes = get_bot_languages("discord")
        else:
            active_codes = get_bot_languages("discord")
        
        for lang in db_langs:
            if lang['code'] in active_codes:
                self.add_item(WelcomeTranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
