# blush cry dance lewd pout shrug sleepy smile smug thumbsup wag thinking triggered teehee deredere thonking scoff happy thumbs grin
import discord
from discord.ext import commands
from utils import sql_commands as mydb
from random import choice


class Emotes(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.emotes = {
            "blush": ["https://media.giphy.com/media/3o6Zt6ML6BklcajjsA/giphy.gif"],
            "cry": ["https://media.giphy.com/media/ROF8OQvDmxytW/giphy.gif"],
            "dance": ["https://media.giphy.com/media/l0MYt5jPR6QX5pnqM/giphy.gif"],
            # ...add more emotes...
        }
        self.emote_packs = {
            "happy": ["smile", "grin", "thumbsup"],
            "sleepy": ["sleepy", "yawn"],
            # ...add more packs...
        }
        self.cooldowns = {}  # {user_id: {emote: timestamp}}
        self.emote_usage = {}  # {user_id: {emote: count}}
        self.unlocked_emotes = {}  # {user_id: set(emote_names)}
        self.pending_emotes = []  # [(user_id, emote_name, url)]

    # --- Emote Command for Each Emote ---
    @commands.command(name="emote")
    async def emote(self, ctx, emote_name: str, member: discord.Member = None):
        """Send an emote GIF, optionally mentioning a user."""
        emote = emote_name.lower()
        # Economy/level check
        if emote not in self.emotes and emote not in self.get_custom_emotes():
            await ctx.send("Unknown emote.")
            return
        if not self.has_unlocked(ctx.author.id, emote):
            await ctx.send("You haven't unlocked this emote yet!")
            return

        # Cooldown check (10s per emote per user)
        import time

        now = time.time()
        user_cooldowns = self.cooldowns.setdefault(ctx.author.id, {})
        if emote in user_cooldowns and now - user_cooldowns[emote] < 10:
            await ctx.send("You're using that emote too quickly!")
            return
        user_cooldowns[emote] = now

        # Usage tracking
        user_usage = self.emote_usage.setdefault(ctx.author.id, {})
        user_usage[emote] = user_usage.get(emote, 0) + 1

        url = choice(self.emotes.get(emote, self.get_custom_emotes().get(emote, [""])))
        mention = member.mention if member else ""
        await ctx.send(
            f"{ctx.author.mention} {mention}", embed=discord.Embed().set_image(url=url)
        )

    # --- Individual Emote Commands (e.g., !blush, !cry, !dance) ---
    # Dynamically add a command for each emote
    def __init_subclass__(cls):
        def make_emote_cmd(emote):
            async def _cmd(self, ctx, member: discord.Member = None):
                await self.emote(ctx, emote, member)

            return _cmd

        for emote in ["blush", "cry", "dance"]:  # Add all your emote names here
            setattr(cls, emote, commands.command(name=emote)(make_emote_cmd(emote)))

    # --- Emote Combos ---
    @commands.command(name="emotecombo")
    async def emote_combo(self, ctx, *emotes):
        """Send multiple emotes in one message."""
        urls = []
        for emote in emotes:
            if self.has_unlocked(ctx.author.id, emote) and (
                emote in self.emotes or emote in self.get_custom_emotes()
            ):
                urls.append(
                    choice(
                        self.emotes.get(
                            emote, self.get_custom_emotes().get(emote, [""])
                        )
                    )
                )
        if not urls:
            await ctx.send("No valid emotes found.")
            return
        for url in urls:
            embed = discord.Embed().set_image(url=url)
            await ctx.send(embed=embed)

    # --- Emote Packs ---
    @commands.command(name="emotepack")
    async def emote_pack(self, ctx, pack_name: str):
        """Send all emotes from a pack."""
        pack = self.emote_packs.get(pack_name.lower())
        if not pack:
            await ctx.send("Unknown emote pack.")
            return
        for emote in pack:
            if self.has_unlocked(ctx.author.id, emote) and (
                emote in self.emotes or emote in self.get_custom_emotes()
            ):
                url = choice(
                    self.emotes.get(emote, self.get_custom_emotes().get(emote, [""]))
                )
                await ctx.send(embed=discord.Embed().set_image(url=url))

    # --- Emote Leaderboard ---
    @commands.command(name="emoteleaderboard")
    async def emote_leaderboard(self, ctx):
        """Show top emote users."""
        leaderboard = sorted(
            ((uid, sum(uses.values())) for uid, uses in self.emote_usage.items()),
            key=lambda x: x[1],
            reverse=True,
        )[:10]
        desc = ""
        for i, (uid, count) in enumerate(leaderboard, 1):
            user = self.client.get_user(uid)
            desc += f"{i}. {user.mention if user else uid}: {count} emotes\n"
        await ctx.send(
            embed=discord.Embed(
                title="Emote Leaderboard", description=desc or "No data."
            )
        )

    # --- Emote Reactions ---
    @commands.command(name="react")
    async def react(self, ctx, emote_name: str, message_id: int):
        """React to a message with an emote (as emoji if available)."""
        emote = emote_name.lower()
        try:
            msg = await ctx.channel.fetch_message(message_id)
            # If you have custom emoji, use them; else, fallback to unicode or skip
            await msg.add_reaction("😄")  # Replace with actual emoji logic
            await ctx.send("Reacted!")
        except Exception:
            await ctx.send("Could not react to that message.")

    # --- Custom Emotes Submission ---
    @commands.command(name="submit_emote")
    async def submit_emote(self, ctx, emote_name: str, url: str):
        """Submit a custom emote for approval."""
        self.pending_emotes.append((ctx.author.id, emote_name, url))
        await ctx.send(
            f"Emote `{emote_name}` submitted for approval! (Admins: review pending list)"
        )

    def get_custom_emotes(self):
        # In production, load from DB or approved list
        return {}

    # --- Unlock Emotes with Level/Economy ---
    @commands.command(name="unlock_emote")
    async def unlock_emote(self, ctx, emote_name: str):
        """Unlock an emote using currency or level."""
        # Example: check user balance/level, deduct cost, unlock emote
        # Replace with your actual economy/level logic
        user_id = ctx.author.id
        unlocked = self.unlocked_emotes.setdefault(user_id, set())
        unlocked.add(emote_name)
        await ctx.send(f"Emote `{emote_name}` unlocked!")

    def has_unlocked(self, user_id, emote_name):
        # Always unlocked for now, add logic for locked emotes
        return True


async def setup(client):
    await client.add_cog(Emotes(client))
