# froscord/voice/panel.py
import discord
from .state import TEMP_VC, TEMP_MUTED

# ───────────────── 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"):
    name = discord.ui.TextInput(label="New channel name", max_length=100)

    def __init__(self, vc_id: int):
        super().__init__()
        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.name.value)
        await interaction.response.send_message(
            f"✏️ Renamed to **{self.name.value}**",
            ephemeral=True,
        )


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

    def __init__(self, vc_id: int):
        super().__init__()
        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,
        )


# ───────────────── MEMBER SELECT ─────────────────

class MemberSelect(discord.ui.UserSelect):
    def __init__(self, vc_id: int, action: str):
        super().__init__(placeholder="Select a member", min_values=1, max_values=1)
        self.vc_id = vc_id
        self.action = action

    async def callback(self, interaction: discord.Interaction):
        vc = interaction.guild.get_channel(self.vc_id)
        member = self.values[0]

        if not vc or member not in vc.members:
            return await interaction.response.send_message(
                "❌ Member is not in this voice channel.",
                ephemeral=True,
            )

        if member.bot or member == interaction.user:
            return await interaction.response.send_message(
                "❌ Invalid target.",
                ephemeral=True,
            )

        # ── MUTE ──
        if self.action == "mute":
            if member.voice and member.voice.channel:
                try:
                    await member.edit(mute=True)
                    TEMP_MUTED.setdefault(vc.id, set()).add(member.id)
                    msg = f"🔇 Muted {member.mention}"
                except discord.HTTPException:
                    msg = "❌ Failed to mute member."
            else:
                msg = "❌ Member is not connected to voice."

        # ── REMOVE ──
        elif self.action == "remove":
            try:
                await member.move_to(None)
                msg = f"🚪 Removed {member.mention}"
            except discord.HTTPException:
                msg = "❌ Failed to remove member."

        await interaction.response.send_message(msg, ephemeral=True)


class MemberActionView(discord.ui.View):
    def __init__(self, vc_id: int, action: str):
        super().__init__(timeout=30)
        self.add_item(MemberSelect(vc_id, action))


# ───────────────── CONTROL PANEL ─────────────────

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

    # ───── OWNER CHECK ─────
    async def interaction_check(self, interaction: discord.Interaction):
        data = TEMP_VC.get(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

    # ───── REFRESH PANEL ─────
    async def refresh(self, interaction: discord.Interaction):
        data = TEMP_VC.get(self.vc_id)
        if not data:
            return

        vc = interaction.guild.get_channel(self.vc_id)
        if not vc:
            return

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

        try:
            msg = await interaction.channel.fetch_message(data["message"])
        except discord.NotFound:
            return

        await msg.edit(
            embed=voice_embed(vc, owner),
            view=VoiceControl(self.vc_id),
        )

    # ───── ACCESS ─────
    @discord.ui.button(label="Lock", emoji="🔒", style=discord.ButtonStyle.secondary)
    async def lock(self, interaction: discord.Interaction, _):
        vc = interaction.guild.get_channel(self.vc_id)
        await vc.set_permissions(interaction.guild.default_role, connect=False)
        await interaction.response.send_message("🔒 Locked", ephemeral=True)
        await self.refresh(interaction)

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

    # ───── MEMBER CONTROL ─────
    @discord.ui.button(label="Mute", emoji="🔇", style=discord.ButtonStyle.primary)
    async def mute(self, interaction: discord.Interaction, _):
        await interaction.response.send_message(
            "Select a member to mute:",
            view=MemberActionView(self.vc_id, "mute"),
            ephemeral=True,
        )

    @discord.ui.button(label="Remove", emoji="🚪", style=discord.ButtonStyle.danger)
    async def remove(self, interaction: discord.Interaction, _):
        await interaction.response.send_message(
            "Select a member to remove:",
            view=MemberActionView(self.vc_id, "remove"),
            ephemeral=True,
        )

    # ───── OWNER ACTIONS ─────
    @discord.ui.button(label="Rename", emoji="✏️", style=discord.ButtonStyle.secondary)
    async def rename(self, interaction: discord.Interaction, _):
        await interaction.response.send_modal(RenameVCModal(self.vc_id))

    @discord.ui.button(label="Limit", emoji="👥", style=discord.ButtonStyle.secondary)
    async def limit(self, interaction: discord.Interaction, _):
        await interaction.response.send_modal(LimitVCModal(self.vc_id))

    @discord.ui.button(label="Delete", emoji="🗑️", style=discord.ButtonStyle.danger)
    async def delete(self, interaction: discord.Interaction, _):
        vc = interaction.guild.get_channel(self.vc_id)
        await interaction.response.send_message(
            "🗑️ Voice channel deleted.",
            ephemeral=True,
        )

        if vc:
            try:
                await vc.delete()
            except discord.NotFound:
                pass

        TEMP_VC.pop(self.vc_id, None)
        TEMP_MUTED.pop(self.vc_id, None)