import os
import asyncio
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from AbhiCalls.thumbnails import get_thumb

QUEUE_DELETE_AFTER = 30
VC_END_DELETE_AFTER = 10


# =================================
# BUTTONS
# =================================
def control_buttons():
    texts = os.getenv("TEXTS")
    links = os.getenv("LINKS")

    buttons = [[
        InlineKeyboardButton("▷", callback_data="vc_resume"),
        InlineKeyboardButton("II", callback_data="vc_pause"),
        InlineKeyboardButton("▢", callback_data="vc_end"),
        InlineKeyboardButton("‣‣I", callback_data="vc_skip"),
    ]]

    if texts and links:
        text_list = [t.strip() for t in texts.split(",")]
        link_list = [l.strip() for l in links.split(",")]

        row = []
        for t, l in zip(text_list, link_list):
            if t and l:
                row.append(InlineKeyboardButton(t, url=l))
                if len(row) == 2:
                    buttons.append(row)
                    row = []

        if row:
            buttons.append(row)

    return InlineKeyboardMarkup(buttons)


class Plugin:
    name = "base"

    def __init__(self, app):
        self.app = app
        self.now_playing_msg = {}

    # =================================
    # NOW PLAYING
    # =================================
    async def on_song_start(self, chat_id, song):
        caption = (
            "▶️ Nᴏᴡ Pʟᴀʏɪɴɢ\n\n"
            f"🎵 Tɪᴛʟᴇ : [{song.title[:19]}]({song.url if song.url else '#'})\n"
            f"⏱ Dᴜʀᴀᴛɪᴏɴ : {song.duration_text}\n"
            f"🙋 Rᴇǫᴜᴇsᴛᴇᴅ Bʏ : {song.requested_by}"
        )

        old = self.now_playing_msg.get(chat_id)
        if old:
            try:
                await old.delete()
            except:
                pass

        try:
            thumb = await get_thumb(
                title=song.title,
                duration=song.duration_text,
                thumbnail=song.thumb,
                channel=getattr(song, "channel", "YouTube"),
                views=getattr(song, "views", "Unknown"),
                videoid="np"
            )

            msg = await self.app.send_photo(
                chat_id,
                photo=thumb,
                caption=caption,
                reply_markup=control_buttons()
            )

            self.now_playing_msg[chat_id] = msg

        except Exception as e:
            print(f"[Plugin:NowPlayingSend] {e}")

    # =================================
    # SEEK
    # =================================
    async def on_seek(self, chat_id, song, seconds):
        msg = self.now_playing_msg.get(chat_id)
        if not msg:
            return

        try:
            direction = "⏩ Fᴏʀᴡᴀʀᴅᴇᴅ" if seconds > 0 else "⏪ Rᴇᴡɪɴᴅᴇᴅ"

            caption = (
                f"{direction} {abs(seconds)}s\n\n"
                "▶️ Nᴏᴡ Pʟᴀʏɪɴɢ\n\n"
                f"🎵 Tɪᴛʟᴇ : [{song.title[:19]}]({song.url if song.url else '#'})\n"
                f"⏱ Dᴜʀᴀᴛɪᴏɴ : {song.duration_text}\n"
                f"🙋 Rᴇǫᴜᴇsᴛᴇᴅ Bʏ : {song.requested_by}"
            )

            try:
                await msg.delete()
            except:
                pass

            thumb = await get_thumb(
                title=song.title,
                duration=song.duration_text,
                thumbnail=song.thumb,
                channel=getattr(song, "channel", "YouTube"),
                views=getattr(song, "views", "Unknown"),
                videoid="seek"
            )

            new_msg = await self.app.send_photo(
                chat_id,
                photo=thumb,
                caption=caption,
                reply_markup=control_buttons()
            )

            self.now_playing_msg[chat_id] = new_msg

        except Exception as e:
            print(f"[Plugin:SeekSend] {e}")

    # =================================
    # SONG END
    # =================================
    async def on_song_end(self, chat_id, song):
        msg = self.now_playing_msg.pop(chat_id, None)
        if msg:
            try:
                await msg.delete()
            except:
                pass

    # =================================
    # QUEUE ADD
    # =================================
    async def on_queue_add(self, chat_id, song, position):
        if position == 1:
            return

        caption = (
            "➕ Aᴅᴅᴇᴅ Tᴏ Qᴜᴇᴜᴇ\n\n"
            f"🎵 Tɪᴛʟᴇ : [{song.title[:30]}]({song.url if song.url else '#'})\n"
            f"⏱ Dᴜʀᴀᴛɪᴏɴ : {song.duration_text}\n"
            f"🙋 Rᴇǫᴜᴇsᴛᴇᴅ Bʏ : {song.requested_by}\n"
            f"📍 Pᴏsɪᴛɪᴏɴ : {position}"
        )

        try:
            thumb = await get_thumb(
                title=song.title,
                duration=song.duration_text,
                thumbnail=song.thumb,
                channel=getattr(song, "channel", "YouTube"),
                views=getattr(song, "views", "Unknown"),
                videoid="queue"
            )

            msg = await self.app.send_photo(
                chat_id,
                photo=thumb,
                caption=caption
            )

            asyncio.create_task(self._auto_delete(msg, QUEUE_DELETE_AFTER))

        except Exception as e:
            print(f"[Plugin:QueueSend] {e}")

    # =================================
    # VC CLOSED
    # =================================
    async def on_vc_closed(self, chat_id):
        msg = self.now_playing_msg.pop(chat_id, None)
        if msg:
            try:
                await msg.delete()
            except:
                pass

        try:
            msg = await self.app.send_message(
                chat_id,
                "🔴 Vᴏɪᴄᴇ Cʜᴀᴛ Eɴᴅᴇᴅ\n\n"
                "🧹 Qᴜᴇᴜᴇ Cʟᴇᴀʀᴇᴅ & Pʟᴀʏᴇʀ Sᴛᴏᴘᴘᴇᴅ."
            )
            asyncio.create_task(self._auto_delete(msg, VC_END_DELETE_AFTER))
        except Exception as e:
            print(f"[Plugin:CloseMsg] {e}")

    # =================================
    # AUTO DELETE
    # =================================
    async def _auto_delete(self, msg, delay):
        try:
            await asyncio.sleep(delay)
            await msg.delete()
        except:
            pass
