from telegram import Update
from telegram.ext import ContextTypes
from config import GROUP_IDS
from services.promo_service import create_promo, create_promo_percent, get_all_promos
from services.link_service import get_links_grouped_by_group, find_link, revoke_link
from services.auth_service import is_admin, is_owner


import re

async def buat_promo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_owner(update.effective_user.id):
        return
    args = context.args
    if len(args) != 3:
        await update.effective_message.reply_text(
            "⚠️ <b>Format salah!</b>\n\n"
            "Promo harga tetap:\n<code>/promo KODE KUOTA HARGA</code>\n\n"
            "Promo persen (untuk Take All):\n<code>/promo KODE KUOTA PERSEN%</code>\n\n"
            "Contoh:\n<code>/promo HEMAT30 5 30%</code>",
            parse_mode="HTML"
        )
        return
    kode = args[0].upper()
    try:
        kuota = int(args[1])
    except ValueError:
        await update.effective_message.reply_text("❌ Kuota harus berupa angka!")
        return

    nilai_str = args[2]
    from telegram import InlineKeyboardButton, InlineKeyboardMarkup

    if nilai_str.endswith("%"):
        try:
            persen = int(nilai_str.rstrip("%"))
        except ValueError:
            await update.effective_message.reply_text("❌ Persen harus berupa angka, contoh: 30%")
            return
        create_promo_percent(kode, kuota, persen)
        await update.effective_message.reply_text(
            f"✅ <b>Promo Persen Berhasil Dibuat!</b>\n\n"
            f"🎟️ Kode: <b>{kode}</b>\n"
            f"👥 Kuota: {kuota} orang\n"
            f"🏷️ Diskon: {persen}% (berlaku untuk Take All)",
            parse_mode="HTML",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_product")
            ]])
        )
    else:
        try:
            harga = int(nilai_str)
        except ValueError:
            await update.effective_message.reply_text("❌ Harga harus berupa angka!")
            return
        create_promo(kode, kuota, harga)
        await update.effective_message.reply_text(
            f"✅ <b>Promo Berhasil Dibuat!</b>\n\n"
            f"🎟️ Kode: <b>{kode}</b>\n"
            f"👥 Kuota: {kuota} orang\n"
            f"💰 Harga Diskon: Rp {harga}",
            parse_mode="HTML",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_product")
            ]])
        )
async def cek_promo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id):
        return
    promos = get_all_promos()
    if not promos:
        await update.effective_message.reply_text("Belum ada kode promo yang aktif.")
        return
    teks = "📊 <b>DAFTAR KODE PROMO AKTIF</b>\n\n"
    for kode, data in promos.items():
        sisa = data["kuota"] - data["terpakai"]
        if data.get("type") == "percent":
            nilai = f"Diskon {data['persen']}%"
        else:
            nilai = f"Rp {data.get('harga', '-')}"
        teks += f"🎟️ <b>{kode}</b>\n💰 {nilai}\n👥 Sisa Kuota: {sisa} / {data['kuota']}\n\n"
    await update.effective_message.reply_text(teks, parse_mode="HTML")

async def list_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id):
        return
    grouped = get_links_grouped_by_group()
    if not grouped:
        await update.effective_message.reply_text("Belum ada link aktif saat ini.")
        return
    teks = "🔗 <b>DAFTAR LINK AKTIF PER GRUP:</b>\n\n"
    for grup, links in grouped.items():
        teks += f"📌 <b>{grup}</b> (Total: {len(links)} Link)\n"
        for item in links:
            teks += f" ├ 👤 ID: <code>{item['user_id']}</code>\n"
            if item.get("promo"):
                teks += f" ├ 🎟️ Promo: <b>{item['promo']}</b>\n"
            teks += f" └ 🔗 {item['link']}\n"
        teks += "\n"
    if len(teks) > 4000:
        teks = teks[:4000] + "\n... (Terpotong karena batas karakter Telegram)"
    await update.effective_message.reply_text(
        teks,
        parse_mode="HTML",
        disable_web_page_preview=True,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_info")
        ]])
    )

async def hapus_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_owner(update.effective_user.id):
        return
    if not context.args:
        await update.effective_message.reply_text("⚠️ <b>Format salah!</b>\n\nGunakan format:\n/hapuslink <code>URL_LINK_NYA</code>", parse_mode="HTML")
        return
    link_target = context.args[0]
    link_data = find_link(link_target)
    if not link_data:
        await update.effective_message.reply_text("❌ Link tidak ditemukan di database aktif.")
        return
    try:
        await context.bot.revoke_chat_invite_link(chat_id=link_data["chat_id"], invite_link=link_target)
        revoke_link(link_data)
        # Kick user dari grup
        try:
            await context.bot.ban_chat_member(chat_id=link_data["chat_id"], user_id=link_data["user_id"])
            await context.bot.unban_chat_member(chat_id=link_data["chat_id"], user_id=link_data["user_id"])
            pesan_kick = f"\n👢 User ID {link_data['user_id']} berhasil dikeluarkan (dikick) dari grup."
        except Exception:
            pesan_kick = f"\n⚠️ User gagal dikeluarkan (Mungkin belum bergabung, sudah keluar sendiri, atau bot tidak punya hak 'Ban Users')."
        await update.effective_message.reply_text(
            f"✅ Link berhasil dihapus/hangus (Revoked) dari grup {link_data['group_name']}.{pesan_kick}",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_product")
            ]])
        )
    except Exception as e:
        await update.effective_message.reply_text(f"⚠️ Gagal menghapus link: {e}")

async def edit_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_owner(update.effective_user.id):
        return
    if len(context.args) < 2:
        await update.effective_message.reply_text("⚠️ <b>Format salah!</b>\n\nGunakan format:\n/editlink <code>URL_LINK_NYA</code> <code>LIMIT_BARU</code>\n\nContoh:\n/editlink https://t.me/+AbCdEfG 3", parse_mode="HTML")
        return
    link_target = context.args[0]
    try:
        new_limit = int(context.args[1])
    except ValueError:
        await update.effective_message.reply_text("❌ Limit baru harus berupa angka!")
        return
    link_data = find_link(link_target)
    if not link_data:
        await update.effective_message.reply_text("❌ Link tidak ditemukan di database aktif.")
        return
    try:
        await context.bot.edit_chat_invite_link(chat_id=link_data["chat_id"], invite_link=link_target, member_limit=new_limit)
        await update.effective_message.reply_text(
            f"✅ Link berhasil diedit!\nBatas join baru: {new_limit} orang.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_product")
            ]])
        )
    except Exception as e:
        await update.effective_message.reply_text(f"⚠️ Gagal mengedit link: {e}")

async def info_grup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id):
        return
    teks = "📊 <b>INFO TOTAL MEMBER GRUP VIP</b>\n\n"
    for nama_grup, id_grup in GROUP_IDS.items():
        try:
            count = await context.bot.get_chat_member_count(id_grup)
            teks += f"📌 <b>{nama_grup}</b>\n👥 Total Member: <b>{count} Orang</b>\n\n"
        except Exception:
            teks += f"📌 <b>{nama_grup}</b>\n⚠️ Gagal menarik data. (Pastikan bot adalah Admin di grup ini)\n\n"
    await update.effective_message.reply_text(teks, parse_mode="HTML")

async def cek_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not is_admin(update.effective_user.id):
        return
    if not context.args:
        await update.effective_message.reply_text(
            "⚠️ <b>Format salah!</b>\n\nGunakan format:\n<code>/cekuser ID_PEMBELI</code>",
            parse_mode="HTML"
        )
        return
    try:
        user_id = int(context.args[0])
    except ValueError:
        await update.effective_message.reply_text("❌ ID User harus berupa Angka!")
        return

    await _do_cek_user(update, context, user_id)


async def _do_cek_user(update, context, user_id: int):
    from telegram import InlineKeyboardButton, InlineKeyboardMarkup
    from services.vip_service import get_all_packages
    from services.link_service import get_links_by_user_id

    packages = get_all_packages()
    seen = {}
    for pkg in packages:
        if pkg.get("group_id"):
            seen[pkg["group_id"]] = pkg["nama"]

    teks = f"🔍 <b>HASIL CEK USER:</b> <code>{user_id}</code>\n\n"

    if not seen:
        teks += "⚠️ Belum ada paket VIP dengan Group ID terdaftar."
    else:
        for group_id, nama in seen.items():
            try:
                member = await context.bot.get_chat_member(chat_id=group_id, user_id=user_id)
                if member.status in ["member", "administrator", "creator"]:
                    teks += f"✅ <b>{nama}</b>: Masih di grup\n"
                elif member.status == "left":
                    teks += f"❌ <b>{nama}</b>: Sudah keluar\n"
                elif member.status == "kicked":
                    teks += f"⛔ <b>{nama}</b>: Dikeluarkan\n"
                else:
                    teks += f"❓ <b>{nama}</b>: Status tidak diketahui\n"
            except Exception:
                teks += f"➖ <b>{nama}</b>: Tidak ditemukan\n"

    user_links = get_links_by_user_id(user_id)
    if user_links:
        teks += "\n─────────────────────\n"
        teks += "🔗 <b>DATA LINK:</b>\n\n"
        for item in user_links:
            status_icon = "✅" if item["status"] == "Aktif" else "❌"
            teks += f"{status_icon} <b>{item['group_name']}</b>\n"
            teks += f"└ 🔗 {item['link']}\n"
            teks += f"└ 📅 {item['join_date'][:10]}\n"
            if item.get("promo"):
                teks += f"└ 🎟️ Promo: {item['promo']}\n"
            teks += "\n"
    else:
        teks += "\n─────────────────────\n"
        teks += "🔗 <b>DATA LINK:</b> Tidak ada\n"

    await update.effective_message.reply_text(
        teks,
        parse_mode="HTML",
        disable_web_page_preview=True,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_info")
        ]])
    )