import discord
from discord.ext import commands
from discord import app_commands
from Utils.cosmetics import *
from Utils.register import *
from Utils.points import *
from Utils.cookies import *
import sys
from datetime import datetime

class TriviaView(discord.ui.View):
    def __init__(self, answers):
        super().__init__()
        self.answers = answers
        for i, answer in enumerate(answers):
            button = discord.ui.Button(style=discord.ButtonStyle.secondary, label=answer, custom_id=str(i))
            self.add_item(button)

    

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

    @commands.hybrid_command(name="snowball", description="Throw a snowball at someone!")
    @app_commands.describe(member='the member you want to throw a snowball at')
    async def snowball(self, ctx: commands.Context, member: discord.Member):
        try:
            await register_user(ctx.author.id)

            if member == ctx.author:
                emoji = await get_emoji(ctx.author.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"It's way more fun to toss one at a friend. Try aiming at someone else, and let the snowball fight begin! ❄️", color=color)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed, delete_after=10)
                return
            if member.bot:
                emoji = await get_emoji(ctx.author.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"You can't throw a snowball at a bot!", color=color)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed, delete_after=10)
                return
            else:            
                await register_user(member.id)
                points = await calc_points(ctx.author.id, ctx.guild)
                emoji = await get_emoji(ctx.author.id)
                emoji_member = await get_emoji(member.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"You threw a snowball at {emoji_member} {member.mention}!", color=color)
                embed.set_footer(text=f"Points received: {points}", icon_url=self.bot.user.avatar)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed)
        except Exception as e:
            print(f"Error: {e} on line {sys.exc_info()[-1].tb_lineno}")
           

    @commands.hybrid_group(name="cookie", description="Give someone cookies!")
    async def cookie(self, ctx: commands.Context):
        #send help message
        if ctx.subcommand_passed is None:
            await ctx.send_help("cookie")
            return

    @cookie.command(name="give", description="Give someone cookies!")
    @app_commands.describe(member='the member you want to give cookies to')
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def give(self, ctx: commands.Context, member: discord.Member):
        try:
            await register_member(ctx.author.id, ctx.guild.id)
            await register_user(ctx.author.id)

            if member == ctx.author:
                emoji = await get_emoji(ctx.author.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"Sharing is caring! Try giving cookies to someone else. 🍪🥛", color=color)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed, delete_after=10)
                return
            if member.bot:
                emoji = await get_emoji(ctx.author.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"You can't give cookies to a bot!", color=color)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed, delete_after=10)
                return
            else:
                await register_user(member.id)
                points = await calc_points(ctx.author.id, ctx.guild)
                emoji_member = await get_emoji(member.id)
                emoji = await get_emoji(ctx.author.id)
                color = await get_color(ctx.author.id)
                color = int(color, 16)
                embed = discord.Embed(description=f"You gave a cookie to {emoji_member} {member.mention}!", color=color)
                embed.set_footer(text=f"Points received: {points}", icon_url=self.bot.user.avatar)
                if emoji:
                    emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
                else:
                    emoji_url = ctx.author.avatar
                embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
                await register_member(member.id, ctx.guild.id)
                await add_cookie(member.id, ctx.guild.id, 1)
                if ctx.interaction:
                    await ctx.interaction.followup.send(embed=embed)
                else:
                    await ctx.reply(embed=embed)
        except Exception as e:
            print(f"Error: {e} on line {sys.exc_info()[-1].tb_lineno}, File: fun.py")

    @give.error
    async def give_error(self, ctx: commands.Context, error: commands.CommandError):
        if ctx.interaction:
            await ctx.defer()
        if isinstance(error, commands.CommandOnCooldown):
            emoji = await get_emoji(ctx.author.id)
            color = await get_color(ctx.author.id)
            color = int(color, 16)
            embed = discord.Embed(description=f"You can give cookies again <t:{datetime.now().timestamp() + error.retry_after:.0f}:R>.\n🎄 Please wait a bit before spreading more holiday cheer! 🎅", color=color)
            if emoji:
                emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
            else:
                emoji_url = ctx.author.avatar
            embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
            if ctx.interaction:
                await ctx.interaction.followup.send(embed=embed)
            else:
                await ctx.reply(embed=embed, delete_after=10)

    @cookie.command(name="check", description="Check how many cookies you have!")
    async def check(self, ctx: commands.Context, member: discord.Member = None):
        try:

            if not member:
                member = ctx.author
            await register_user(member.id)
            await register_member(member.id, ctx.guild.id)
            cookies = await get_cookie(member.id, ctx.guild.id)
            points = await calc_points(ctx.author.id, ctx.guild)
            emoji = await get_emoji(ctx.author.id)
            emoji_member = await get_emoji(member.id)
            color = await get_color(ctx.author.id)
            color = int(color, 16)
            embed = discord.Embed(description=("You have" if member == ctx.author else (emoji_member + " " + member.mention + " has"))  + f" `{cookies}` cookies! 🍪", color=color)
            if emoji:
                emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
            else:
                emoji_url = ctx.author.avatar
            embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
            embed.set_footer(text=f"Points received: {points}", icon_url=self.bot.user.avatar)

            if ctx.interaction:
                await ctx.interaction.followup.send(embed=embed)
            else:
                await ctx.reply(embed=embed)
        except Exception as e:
            print(f"Error: {e} on line {sys.exc_info()[-1].tb_lineno}, File: fun.py")

    @cookie.command(name="leaderboard", description="Check the cookie leaderboard!")
    async def leaderboard(self, ctx: commands.Context):
        try:

            await register_user(ctx.author.id)
            await register_member(ctx.author.id, ctx.guild.id)
            connection = mysql.connector.connect(
                host="arclightbot.com",
                user=getenv("DB_USER"),
                password=getenv("DB_PASSWORD"),
                database=f"christmas"
            )
            cursor = connection.cursor()
            cursor.execute(f"SELECT users FROM guilds WHERE id = %s", (ctx.guild.id,))
            result = cursor.fetchone()
            users = result[0]
            json_users = json.loads(users)
            sorted_users = sorted(json_users.items(), key=lambda x: x[1]["cookies"], reverse=True)
            color = await get_color(ctx.author.id)
            color = int(color, 16)
            points = await calc_points(ctx.author.id, ctx.guild)
            embed = discord.Embed(title="🍪 Cookie Leaderboard", color=color)
            formated_users = []
            for i, user in enumerate(sorted_users):
                member = ctx.guild.get_member(int(user[0]))
                if member:
                    emoji_user = await get_emoji(member.id)
                    formated_users.append(f"{i+1}. {(emoji_user + " ") if emoji_user else ""}{member.mention} - `{user[1]['cookies']}`")
            embed.description = "\n".join(formated_users)
            embed.set_footer(text=f"Points received: {points}", icon_url=self.bot.user.avatar)

            if ctx.interaction:
                await ctx.interaction.followup.send(embed=embed)
            else:
                await ctx.reply(embed=embed)
        except Exception as e:
            print(f"Error: {e} on line {sys.exc_info()[-1].tb_lineno}, File: fun.py")

    @commands.hybrid_command(name="trivia", description="Answer a trivia question!")
    async def trivia(self, ctx: commands.Context):
        try:
            await register_user(ctx.author.id)
            points = await calc_points(ctx.author.id, ctx.guild)
            emoji = await get_emoji(ctx.author.id)
            color = await get_color(ctx.author.id)
            color = int(color, 16)
            with open("Utils/questions.json", "r") as f:
                questions = json.load(f)
            question = random.choice(list(questions["questions"]))
            question_text = question["question"]
            answers = question["answers"]
            correct_answer = question["correct_answer"]
            embed = discord.Embed(description=question_text, color=color)
            embed.set_footer(text=f"Points received: {points}", icon_url=self.bot.user.avatar)
            if emoji:
                emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.strip('<:>').split(':')[1]}.png"
            else:
                emoji_url = ctx.author.avatar
            embed.set_author(name=str(ctx.author.display_name), icon_url=emoji_url)
            view = TriviaView(answers)
            if ctx.interaction:
                msg = await ctx.interaction.followup.send(embed=embed, view=view)
            else:
                msg = await ctx.reply(embed=embed, view=view)
            interaction = await self.bot.wait_for("interaction", check=lambda i: i.user == ctx.author and i.type == discord.InteractionType.component and i.message.id == msg.id)
            await interaction.response.defer()
            if interaction.data["custom_id"] == str(answers.index(correct_answer)):
                embed = interaction.message.embeds[0]
                embed.description = f"{question_text}\n\n**Correct answer:** `{correct_answer}`\n\n**You answered correctly! 🎉**"
                await interaction.message.edit(embed=embed, view=None)
            else:
                embed = interaction.message.embeds[0]
                embed.description = f"{question_text}\n\n**Correct answer:** `{correct_answer}`\n\n**You answered incorrectly! 😢**"
                await interaction.message.edit(embed=embed, view=None)
                
        except Exception as e:
            print(f"Error: {e} on line {sys.exc_info()[-1].tb_lineno}, File: fun.py")

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(Fun(bot))


improve and add more fun commands to the code explain what you have changed afterwards