# froscord/voice/panel.py
import discord


# ───────────────── EMBED ─────────────────

def voice_embed(vc: discord.VoiceChannel, owner: discord.Member):
    locked = not vc.permissions_for(vc.guild.default_role).connect

    embed = discord.Embed(
        title="🎧 Voice Channel Control",
        description="Manage **your personal voice channel**",
        color=discord.Color.blurple()
    )

    embed.add_field(name="👑 Owner", value=owner.mention, inline=True)
    embed.add_field(
        name="👥 Members",
        value=f"{len(vc.members)} / {vc.user_limit or '∞'}",
        inline=True
    )
    embed.add_field(
        name="🔒 Status",
        value="Locked" if locked else "Unlocked",
        inline=True
    )

    embed.set_footer(text="Only the VC owner can use this panel")
    return embed


# ───────────────── MODALS ─────────────────

class RenameVCModal(discord.ui.Modal, title="Rename Voice Channel"):
    new_name = discord.ui.TextInput(label="New channel name", max_length=100)

    def __init__(self, manager, vc_id: int):
        super().__init__()
        self.manager = manager
        self.vc_id = vc_id

    async def on_submit(self, interaction: discord.Interaction):
        vc = interaction.guild.get_channel(self.vc_id)
        if not vc:
            return await interaction.response.send_message(
                "❌ Voice channel not found", ephemeral=True
            )

        await vc.edit(name=self.new_name.value)
        await interaction.response.send_message(
            f"✏️ VC renamed to **{self.new_name.value}**", ephemeral=True
        )
        await self.manager.refresh_panel(interaction, self.vc_id)


class LimitVCModal(discord.ui.Modal, title="Set User Limit"):
    limit = discord.ui.TextInput(label="User limit (0 = unlimited)", max_length=2)

    def __init__(self, manager, vc_id: int):
        super().__init__()
        self.manager = manager
        self.vc_id = vc_id

    async def on_submit(self, interaction: discord.Interaction):
        vc = interaction.guild.get_channel(self.vc_id)
        if not vc:
            return await interaction.response.send_message(
                "❌ Voice channel not found", ephemeral=True
            )

        try:
            value = int(self.limit.value)
            if value < 0:
                raise ValueError
        except ValueError:
            return await interaction.response.send_message(
                "❌ Enter a valid number", ephemeral=True
            )

        await vc.edit(user_limit=value)
        await interaction.response.send_message(
            f"👥 User limit set to **{value or '∞'}**", ephemeral=True
        )
        await self.manager.refresh_panel(interaction, self.vc_id)


# ───────────────── VIEW ─────────────────

class VoicePanel(discord.ui.View):
    def __init__(self, manager, vc_id: int):
        super().__init__(timeout=None)
        self.manager = manager
        self.vc_id = vc_id

    async def interaction_check(self, interaction: discord.Interaction):
        data = self.manager.get_vc_data(self.vc_id)
        if not data or interaction.user.id != data["owner"]:
            await interaction.response.send_message(
                "❌ This control panel is not yours.", ephemeral=True
            )
            return False
        return True

    def build_embed(self):
        data = self.manager.get_vc_data(self.vc_id)
        if not data:
            return None

        vc = self.manager.bot.get_channel(self.vc_id)
        if not vc:
            return None

        owner = vc.guild.get_member(data["owner"])
        if not owner:
            return None

        return voice_embed(vc, owner)

    # ───── BUTTONS ─────

    @discord.ui.button(label="Lock", emoji="🔒", style=discord.ButtonStyle.secondary)
    async def lock(self, interaction, button):
        vc = interaction.guild.get_channel(self.vc_id)
        await vc.set_permissions(interaction.guild.default_role, connect=False)
        await interaction.response.send_message("🔒 VC locked", ephemeral=True)
        await self.manager.refresh_panel(interaction, self.vc_id)

    @discord.ui.button(label="Unlock", emoji="🔓", style=discord.ButtonStyle.success)
    async def unlock(self, interaction, button):
        vc = interaction.guild.get_channel(self.vc_id)
        await vc.set_permissions(interaction.guild.default_role, connect=True)
        await interaction.response.send_message("🔓 VC unlocked", ephemeral=True)
        await self.manager.refresh_panel(interaction, self.vc_id)

    @discord.ui.button(label="Rename", emoji="✏️", style=discord.ButtonStyle.primary)
    async def rename(self, interaction, button):
        await interaction.response.send_modal(
            RenameVCModal(self.manager, self.vc_id)
        )

    @discord.ui.button(label="Set Limit", emoji="👥", style=discord.ButtonStyle.primary)
    async def set_limit(self, interaction, button):
        await interaction.response.send_modal(
            LimitVCModal(self.manager, self.vc_id)
        )

    @discord.ui.button(label="Claim", emoji="👑", style=discord.ButtonStyle.secondary)
    async def claim(self, interaction, button):
        data = self.manager.get_vc_data(self.vc_id)
        data["owner"] = interaction.user.id
        await interaction.response.send_message(
            "👑 You are now the owner", ephemeral=True
        )
        await self.manager.refresh_panel(interaction, self.vc_id)

    @discord.ui.button(label="Delete", emoji="🗑️", style=discord.ButtonStyle.danger)
    async def delete(self, interaction, button):
        vc = interaction.guild.get_channel(self.vc_id)
        await vc.delete()
        self.manager.remove_vc(self.vc_id)