import discord
from discord.ext import commands
from discord import ui
from typing import Optional
import logging

# 設置日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('quiz_message_components')

# 設定測驗頻道 ID
# test channel ID = 1304655141097701386
# show channel ID = 1345587506636259409
QUIZ_CHANNEL_ID = 1345587506636259409

class StartQuizButton(ui.Button):
    def __init__(self):
        super().__init__(
            label="開始測驗",
            style=discord.ButtonStyle.primary,
            custom_id="start_quiz"
        )

    async def callback(self, interaction: discord.Interaction):
        # 檢查是否在指定的測驗頻道
        if interaction.channel_id != QUIZ_CHANNEL_ID:
            await interaction.response.send_message("請在指定的測驗頻道中進行測驗！", ephemeral=True)
            return
        
        # 觸發測驗開始
        quiz_cog = interaction.client.get_cog('Quiz')
        if quiz_cog:
            await quiz_cog.start_quiz(interaction)
            logger.info(f" - 訊息欄: {interaction.user} 開啟小測驗")
        else:
            await interaction.response.send_message("Quiz 模組載入失敗，請聯繫管理員！", ephemeral=True)

class StartQuizView(ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.add_item(StartQuizButton())

class MessageComponents(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.quiz_message: Optional[discord.Message] = None

    async def create_quiz_message(self, channel):
        # 建立嵌入訊息
        embed = discord.Embed(
            title="電腦軟體應用檢定學科測驗",
            description="點擊下方按鈕開始測驗！\n測驗將會隨機抽選10題題目。",
            color=discord.Color.blue()
        )
        embed.add_field(
            name="注意事項", 
            value="- 每題都需要作答\n- 作答完畢會顯示測驗結果\n- 可查看答錯的題目",
            inline=False
        )
        
        # 發送嵌入訊息和按鈕
        view = StartQuizView()
        return await channel.send(embed=embed, view=view)
    
    @commands.Cog.listener()
    async def on_ready(self):
        print("MessageComponents cog is ready!")
        # 檢查是否已經有測驗訊息
        channel = self.bot.get_channel(QUIZ_CHANNEL_ID)
        if not channel:
            print(f"找不到頻道 ID: {QUIZ_CHANNEL_ID}")
            return

        try:
            # 清除頻道中的訊息
            await channel.purge()
            
            # 創建新的測驗訊息
            self.quiz_message = await self.create_quiz_message(channel)
            logger.info(f"小測驗按鈕已傳送至 {QUIZ_CHANNEL_ID}")
        except Exception as e:
            print(f"Error creating quiz message: {e}")

async def setup(bot):
    await bot.add_cog(MessageComponents(bot))