from telebot.types import (
    InlineKeyboardButton, InlineKeyboardMarkup,
    ReplyKeyboardMarkup, KeyboardButton,
)
from src.repositories import repo

ADMIN_REPLY_TEXTS = frozenset([
    "📤 Upload", "📁 Media", "📂 Kategori", "📝 Template",
    "📢 Force Subscribe", "👥 User", "📊 Statistik", "📣 Broadcast",
    "⚙️ Pengaturan Bot", "🛡 Sistem", "💾 Backup",
])


def kb(rows):
    markup = InlineKeyboardMarkup()
    callback_prefixes = (
        "adm:", "media:", "cat:", "tpl:", "fs:",
        "usr:", "set:", "verify:", "btn:", "donate:", "sys:", "bct:",
    )
    for row in rows:
        buttons = []
        for text, target in row:
            if target.startswith(callback_prefixes):
                buttons.append(InlineKeyboardButton(text, callback_data=target))
            else:
                buttons.append(InlineKeyboardButton(text, url=target))
        markup.row(*buttons)
    return markup


def admin_home():
    return kb([
        [("📤 Upload", "adm:upload"), ("📁 Media", "adm:media")],
        [("📂 Kategori", "adm:categories"), ("📝 Template", "adm:templates")],
        [("📢 Force Subscribe", "adm:fsubs"), ("👥 User", "adm:users")],
        [("📊 Statistik", "adm:stats"), ("📣 Broadcast", "adm:broadcast")],
        [("⚙️ Pengaturan Bot", "adm:settings"), ("🛡 Sistem", "adm:system")],
        [("💾 Backup", "adm:backup")],
    ])


def admin_home_reply():
    markup = ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    for row_texts in [
        ["📤 Upload", "📁 Media"],
        ["📂 Kategori", "📝 Template"],
        ["📢 Force Subscribe", "👥 User"],
        ["📊 Statistik", "📣 Broadcast"],
        ["⚙️ Pengaturan Bot", "🛡 Sistem"],
        ["💾 Backup"],
    ]:
        markup.row(*[KeyboardButton(t) for t in row_texts])
    return markup


def back(cb="adm:home"):
    return kb([[("⬅️ Kembali", cb)]])


def cancel():
    return kb([[("❌ Batal", "adm:cancel")]])


def welcome():
    rows = []
    for button in repo.buttons():
        if button["setting_key"] == "donation_enabled":
            rows.append([(button["label"], "donate:menu")])
            continue
        url = button["resolved_url"] or button["url"]
        if url:
            rows.append([(button["label"], url)])
    return kb(rows)


def join(code):
    rows = [[(channel["button_text"], channel["invite_link"])] for channel in repo.fsubs()]
    rows.append([("✅ Saya Sudah Bergabung", f"verify:{code}")])
    return kb(rows)


def media_actions(mid):
    return kb([
        [("✏️ Judul", f"media:edit:title:{mid}"), ("📝 Caption", f"media:edit:user_caption:{mid}")],
        [("🖼 Thumbnail", f"media:edit:thumbnail_file_id:{mid}"), ("📄 Nama File", f"media:edit:filename:{mid}")],
        [("📂 Kategori", f"media:category:{mid}"), ("🔄 Posting Ulang", f"media:repost:{mid}")],
        [("🗑 Hapus", f"media:delete:{mid}")],
        [("⬅️ Kembali", "adm:media")],
    ])


def broadcast_skip_media():
    return kb([
        [("⏭ Lewati (tanpa media)", "bct:skip_media")],
        [("❌ Batal", "adm:cancel")],
    ])


def broadcast_skip_button():
    return kb([
        [("⏭ Lewati (tanpa tombol)", "bct:skip_button")],
        [("❌ Batal", "adm:cancel")],
    ])


def broadcast_home(templates):
    rows = []
    for tpl in templates:
        rows.append([
            (f"📣 {tpl['name']}", f"bct:use:{tpl['id']}"),
        ])
    rows.append([("➕ Tambah Template", "bct:add")])
    rows.append([("🗑️ Hapus Template", "bct:delete_list")])
    rows.append([("⬅️ Kembali", "adm:home")])
    return kb(rows)


def broadcast_template_list(templates):
    rows = []
    for tpl in templates:
        rows.append([
            (f"📄 {tpl['name']}", f"bct:view:{tpl['id']}"),
        ])
    rows.append([("➕ Tambah Template", "bct:add")])
    rows.append([("⬅️ Kembali", "bct:home")])
    return kb(rows)


def broadcast_template_view(tid):
    return kb([
        [("✏️ Edit Nama", f"bct:edit_name:{tid}"), ("📝 Edit Konten", f"bct:edit_content:{tid}")],
        [("🗑 Hapus", f"bct:delete:{tid}")],
        [("⬅️ Kembali", "bct:home")],
    ])


def broadcast_delete_list(templates):
    rows = []
    for tpl in templates:
        rows.append([
            (f"🗑️ {tpl['name']}", f"bct:delete:{tpl['id']}"),
        ])
    rows.append([("⬅️ Kembali", "bct:home")])
    return kb(rows)


def broadcast_send_select(templates):
    rows = []
    for i in range(0, len(templates), 2):
        row = [(templates[i]["name"], f"bct:use:{templates[i]['id']}")]
        if i + 1 < len(templates):
            row.append((templates[i + 1]["name"], f"bct:use:{templates[i + 1]['id']}"))
        rows.append(row)
    rows.append([("✍️ Tulis Konten Baru", "bct:send_new")])
    rows.append([("⬅️ Kembali", "bct:home")])
    return kb(rows)


def broadcast_confirm(tid):
    return kb([
        [("✅ Kirim", f"bct:confirm:{tid}"), ("❌ Batal", "bct:home")],
    ])


def broadcast_delete_confirm(tid):
    return kb([
        [("✅ Ya, Hapus", f"bct:delete_ok:{tid}"), ("❌ Batal", "bct:delete_list")],
    ])


def donation_menu():
    return kb([
        [("⭐ 10", "donate:10"), ("⭐ 25", "donate:25")],
        [("⭐ 50", "donate:50"), ("⭐ 100", "donate:100")],
        [("⭐ 250", "donate:250"), ("⭐ 500", "donate:500")],
        [("⬅️ Kembali", "donate:back")],
    ])
