import phonenumbers
from telegram import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
from database import db
from config import ADMIN_IDS

def get_country_flag(country_name: str) -> str:
    flags = {
        "bangladesh": "🇧🇩", "india": "🇮🇳", "usa": "🇺🇸", "indonesia": "🇮🇩", 
        "vietnam": "🇻🇳", "brazil": "🇧🇷", "russia": "🇷🇺", "nigeria": "🇳🇬"
    }
    return flags.get(country_name.lower().strip(), "🌍")

def get_display_number(full_number: str) -> str:
    if db.get_setting("include_cc", "ON") == "ON":
        return full_number
    try:
        parsed = phonenumbers.parse(full_number if full_number.startswith("+") else f"+{full_number}")
        return str(parsed.national_number)
    except:
        return full_number

# --- User Keyboards ---
def main_menu_keyboard(user_id: int):
    kb = [
        [KeyboardButton("📱 Get Number")],
        [KeyboardButton("🏆 Leaderboard"), KeyboardButton("💳 Wallet")],
        [KeyboardButton("🚦 Traffic")]
    ]
    if user_id in ADMIN_IDS:
        kb.append([KeyboardButton("⚙️ Admin Panel")])
    return ReplyKeyboardMarkup(kb, resize_keyboard=True)

def user_services_kb(services: list):
    buttons = []
    row = []
    for srv in services:
        row.append(InlineKeyboardButton(f"📌 {srv.title()}", callback_data=f"usr_srv_{srv}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    return InlineKeyboardMarkup(buttons)

def user_countries_kb(service: str, countries: list):
    buttons = []
    row = []
    for c in countries:
        flag = get_country_flag(c)
        row.append(InlineKeyboardButton(f"{flag} {c.title()}", callback_data=f"usr_cntr_{service}:{c}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    buttons.append([InlineKeyboardButton("🔙 Back to Services", callback_data="user_get_number")])
    return InlineKeyboardMarkup(buttons)

def user_ranges_kb(service: str, country: str, ranges: list):
    buttons = [[InlineKeyboardButton("🚀 Get Any Number (Auto)", callback_data=f"usr_ext_{service}:{country}:AUTO")]]
    row = []
    for r in ranges:
        row.append(InlineKeyboardButton(f"🔢 {r}", callback_data=f"usr_ext_{service}:{country}:{r}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    buttons.append([InlineKeyboardButton("🔙 Back to Countries", callback_data=f"usr_srv_{service}")])
    return InlineKeyboardMarkup(buttons)

# --- Admin Keyboards ---
def admin_keyboard():
    cc_status = db.get_setting("include_cc", "ON")
    timeout = db.get_setting("otp_timeout", 20)
    
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("🛠 Manage Services", callback_data="admin_manage_services")],
        [
            InlineKeyboardButton(f"⏱️ Set Timeout ({timeout}m)", callback_data="admin_timeout"),
            InlineKeyboardButton(f"🌐 Format: {cc_status}", callback_data="admin_toggle_cc")
        ],
        [
            InlineKeyboardButton("🔑 Set API Key", callback_data="admin_set_api"),
            InlineKeyboardButton("🔗 Set Base URL", callback_data="admin_set_url")
        ],
        [
            InlineKeyboardButton("💰 Set OTP Rate", callback_data="admin_otp_rate"),
            InlineKeyboardButton("📞 Set Fetch Limit", callback_data="admin_fetch_limit")
        ],
        [InlineKeyboardButton("❌ Close", callback_data="close_panel")]
    ])

def admin_services_kb(services: list):
    buttons = []
    row = []
    for srv in services:
        row.append(InlineKeyboardButton(f"📌 {srv.title()}", callback_data=f"mng_srv_{srv}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    buttons.append([InlineKeyboardButton("➕ Add Service", callback_data="add_srv"), InlineKeyboardButton("➖ Remove Service", callback_data="rem_srv")])
    buttons.append([InlineKeyboardButton("🔙 Back to Admin", callback_data="admin_main")])
    return InlineKeyboardMarkup(buttons)

def admin_countries_kb(service: str, countries: list):
    buttons = []
    row = []
    for c in countries:
        flag = get_country_flag(c)
        row.append(InlineKeyboardButton(f"{flag} {c.title()}", callback_data=f"mng_cntr_{service}:{c}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    buttons.append([InlineKeyboardButton("➕ Add Country", callback_data=f"add_cntr_{service}"), InlineKeyboardButton("➖ Remove Country", callback_data=f"rem_cntr_{service}")])
    buttons.append([InlineKeyboardButton("🔙 Back to Services", callback_data="admin_manage_services")])
    return InlineKeyboardMarkup(buttons)

def admin_ranges_kb(service: str, country: str, ranges: list):
    buttons = []
    row = []
    for r in ranges:
        row.append(InlineKeyboardButton(f"❌ {r}", callback_data=f"rem_rng_{service}:{country}:{r}"))
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row: buttons.append(row)
    buttons.append([InlineKeyboardButton("➕ Add Range", callback_data=f"add_rng_{service}:{country}")])
    buttons.append([InlineKeyboardButton("🔙 Back to Countries", callback_data=f"mng_srv_{service}")])
    return InlineKeyboardMarkup(buttons)
