import discord
from discord.ext import commands
from discord import ui
from discord.ui import Button, View
import logging

# 設置日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('ButtonSetup')

# 在這裡設置您想要按鈕出現的頻道ID
# test channel ID = 1306873851577106442
# show channel ID = 1345374449376956469
CHANNEL_ID = 1345374449376956469

class ButtonSetup(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        channel = self.bot.get_channel(CHANNEL_ID)
        if channel:
            try:
                # 清除現有消息
                async for message in channel.history(limit=100):
                    await message.delete()
                
                # 創建新的按鈕
                # 提醒事項表單填寫
                view = ReminderFormInput()
                await channel.send(f"請按照格式輸入，並且輸入半形整數數字，否則都預設為0\n點擊下方按鈕來設置提醒事項", view=view)
                logger.info(f"'提醒事項表單填寫'按鈕已傳送至 {CHANNEL_ID}")
                
                # 查詢提醒事項
                from utils.reminder_view import send_reminder
                channel = self.bot.get_channel(CHANNEL_ID)
                await send_reminder(channel, self.bot)
                logger.info(f"'查看提醒事項'按鈕已傳送至 {CHANNEL_ID}")

            except Exception as e:
                logger.error(f"Error in on_ready: {e}")

# 提醒事項表單
class ReminderFormInput(View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="創建提醒事項", style=discord.ButtonStyle.primary, custom_id="create_reminder")
    async def create_reminder(self, interaction: discord.Interaction, button: Button):
        try:
            from cogs.reminder_form_input import ReminderForm
            modal = ReminderForm()
            await interaction.response.send_modal(modal)
            logger.info(f" - 訊息欄: {interaction.user} 開啟提醒事項填寫表單")
        except Exception as e:
            logger.error(f"Error sending modal: {e}")
            try:
                # 嘗試發送錯誤訊息
                await interaction.response.send_message(f"發生錯誤：{str(e)}", ephemeral=True)
            except Exception as follow_up_error:
                logger.error(f"Error sending follow-up error message: {follow_up_error}")

async def setup(bot):
    await bot.add_cog(ButtonSetup(bot))