import discord


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


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)
        owner = vc.guild.get_member(data["owner"])
        return voice_embed(vc, owner)

    # ───── ROW 0 ─────

    @discord.ui.button(
        label="Lock",
        emoji="🔒",
        style=discord.ButtonStyle.secondary,
        row=0
    )
    async def lock(self, interaction, _):
        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,
        row=0
    )
    async def unlock(self, interaction, _):
        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)

    # ───── ROW 1 ─────

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

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

    # ───── ROW 2 ─────

    @discord.ui.button(
        label="Claim",
        emoji="👑",
        style=discord.ButtonStyle.secondary,
        row=2
    )
    async def claim(self, interaction, _):
        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)

    # ───── ROW 3 ─────

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