import os
import html

from telegram import (
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    InputMediaPhoto
)
from services.admin_service import get_vs_enabled_admins
from services.channel_service import get_all_channels
from services.payment_info_service import get_banner_file_id, get_main_caption
from utils.custom_emoji import TELEGRAM_CAPTION_LIMIT, visible_text_length

from config import BANNER_PATH


def _default_main_menu_text(user):
    first_name = html.escape(user.first_name or "User")
    return (
        f"👋 Hai <b>{first_name}</b>!\n\n"
        "Selamat datang di <b>VIP VIRALINMAS</b> 🔥\n\n"
        "Pilih layanan:\n"
        "🛍️ Paket VIP\n"
        "🎥 Talent / VCS\n"
        "🔄 Rejoin Grup\n"
        "👤 My Profile\n"
        "💬 Bantuan Admin\n"
        "📖 Cara Order\n"
        "⭐ Testimoni"
    )


def get_main_menu_text(user):
    caption = get_main_caption()
    if not caption:
        return _default_main_menu_text(user)

    username = f"@{user.username}" if user.username else ""
    return (
        caption
        .replace("{first_name}", html.escape(user.first_name or ""))
        .replace("{username}", html.escape(username))
        .replace("{user_id}", str(user.id))
    )


# def get_main_menu_keyboard():
#     return InlineKeyboardMarkup([
#         [InlineKeyboardButton("🛍️ Menu VIP", callback_data="daftar")],
#         [InlineKeyboardButton("🎥 Menu VS", callback_data="vs_menu")],
#         [
#             InlineKeyboardButton(
#                 "📖 Cara Order",
#                 url="https://t.me/testimoni_viralinmas/54"
#             )
#         ]
#     ])
def get_main_menu_keyboard():

    vs_admins = get_vs_enabled_admins()

    if vs_admins:
        vs_text = "🎥 Talent / VCS ✅"
    else:
        vs_text = "🎥 Talent / VCS ❌"

    channels = get_all_channels()
    testimoni_link = None
    for ch in channels:
        link = ch.get("link") or (f"https://t.me/{ch['username'].lstrip('@')}" if ch.get("username") else None)
        if link:
            testimoni_link = link
            break

    keyboard = [
        [
            InlineKeyboardButton("🛍️ Paket VIP", callback_data="daftar"),
            InlineKeyboardButton(vs_text, callback_data="vs_menu")
        ],
        [
            InlineKeyboardButton("🔄 Rejoin Grup", callback_data="rejoin"),
            InlineKeyboardButton("👤 My Profile", callback_data="user_profile")
        ],
        [
            InlineKeyboardButton("💬 Bantuan Admin", callback_data="contact_admin"),
            InlineKeyboardButton(
                "📖 Cara Order",
                callback_data="cara_order"
            )
        ],
    ]

    if testimoni_link:
        keyboard.append([
            InlineKeyboardButton("⭐ Testimoni", url=testimoni_link)
        ])

    return InlineKeyboardMarkup(keyboard)


async def show_main_menu(message_or_query, user):
    text = get_main_menu_text(user)
    keyboard = get_main_menu_keyboard()

    caption_fits = visible_text_length(text) <= TELEGRAM_CAPTION_LIMIT
    banner = None
    if caption_fits:
        banner = get_banner_file_id() or (open(BANNER_PATH, "rb") if os.path.exists(BANNER_PATH) else None)

    if banner and caption_fits:
        if hasattr(message_or_query, "edit_message_media") and getattr(message_or_query, "message", None) and (
            message_or_query.message.photo or message_or_query.message.video
        ):
            await message_or_query.edit_message_media(
                media=InputMediaPhoto(banner, caption=text, parse_mode="HTML"),
                reply_markup=keyboard
            )
        elif getattr(message_or_query, "message", None):
            try:
                await message_or_query.message.delete()
            except Exception:
                pass
            await message_or_query.message.reply_photo(
                photo=banner,
                caption=text,
                parse_mode="HTML",
                reply_markup=keyboard
            )
        else:
            await message_or_query.reply_photo(
                photo=banner,
                caption=text,
                parse_mode="HTML",
                reply_markup=keyboard
            )
    else:
        if hasattr(message_or_query, "edit_message_text"):
            if getattr(message_or_query, "message", None) and (
                message_or_query.message.photo or message_or_query.message.video
            ):
                try:
                    await message_or_query.message.delete()
                except Exception:
                    pass
                await message_or_query.message.reply_text(
                    text=text,
                    parse_mode="HTML",
                    reply_markup=keyboard
                )
            else:
                await message_or_query.edit_message_text(
                    text=text,
                    parse_mode="HTML",
                    reply_markup=keyboard
                )
        else:
            await message_or_query.reply_text(
                text=text,
                parse_mode="HTML",
                reply_markup=keyboard
            )
