from telegram import Update
from telegram.ext import ContextTypes, CallbackQueryHandler
from database.db import DB
from utils.helpers import money
from utils.keyboards import main_menu_inline, inline
from utils.decorators import anti_flood
from config import REQUIRED_CHANNEL_LINK, ADMIN_USERNAME

async def _render_home(target, tg_user):
    from utils.premium_emoji import (pe, PE_NAME, PE_USER_ID, PE_WALLET,
                                     PE_REF_EARNINGS, PE_ORDERS)
    row = await DB.fetchone("SELECT * FROM users WHERE user_id=?", (tg_user.id,))
    if not row:
        if hasattr(target, "reply_text"):
            await target.reply_text("Please press /start first.")
        return
    text = (
        f"{pe('👤', PE_NAME)} <b>Name:</b> {tg_user.full_name}\n"
        f"{pe('🆔', PE_USER_ID)} <b>ID:</b> <code>{tg_user.id}</code>\n"
        f"{pe('💰', PE_WALLET)} <b>Wallet Balance:</b> {money(row['balance'])}\n"
        f"{pe('🎁', PE_REF_EARNINGS)} <b>Referral Earnings:</b> {money(row['referral_earnings'])}\n"
        f"{pe('📦', PE_ORDERS)} <b>Total Purchases:</b> {money(row['total_purchases'])}\n\n"
        "Choose an option below 👇"
    )
    kb = main_menu_inline(REQUIRED_CHANNEL_LINK)
    if hasattr(target, "edit_message_text"):
        try:
            await target.edit_message_text(text, parse_mode="HTML", reply_markup=kb)
            return
        except Exception:
            pass
    await target.reply_html(text, reply_markup=kb)

@anti_flood
async def dashboard(update: Update, context: ContextTypes.DEFAULT_TYPE):
    target = update.message or update.callback_query.message
    await _render_home(target, update.effective_user)

async def about_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):
    q = update.callback_query; await q.answer()
    text = (
        "🌟 <b>About CartCraft Store</b> 🌟\n\n"
        "Welcome to <b>CartCraft Store</b> — your trusted hub for premium "
        "<b>digital products</b> and <b>subscriptions</b> at unbeatable prices! 💎\n\n"
        "🛍️ <b>What we offer:</b>\n"
        "• 🤖 AI tools — ChatGPT, Claude, Grok, Gemini & more\n"
        "• 🎬 Streaming — Netflix, Spotify, YouTube Premium\n"
        "• 🎨 Creative apps — Adobe, Canva Pro, CapCut Pro\n"
        "• 🛡️ VPNs & Security — NordVPN, Hotspot, and more\n"
        "• 🎮 Gaming — Xbox, Fortnite, Game Pass\n"
        "• ✉️ Accounts — Gmail, Hotmail, social media\n\n"
        "⚡ <b>Why choose us?</b>\n"
        "• 🚀 Instant automatic delivery\n"
        "• 💳 Multiple payment methods (Crypto, Bybit, ⭐ Stars)\n"
        "• 🎁 Earn cash with our referral program\n"
        "• 🛡️ Safe, secure & 24/7 support\n\n"
        f"👑 Admin: @{ADMIN_USERNAME}\n"
        "💬 Need help? Tap <b>Support</b> from the menu."
    )
    await q.edit_message_text(text, parse_mode="HTML",
        reply_markup=inline([[("⬅ Back", "menu:home")]]))

async def home_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):
    q = update.callback_query; await q.answer()
    await _render_home(q, q.from_user)

def menu_callback_handlers():
    return [
        CallbackQueryHandler(home_cb, pattern=r"^menu:home$"),
        CallbackQueryHandler(about_cb, pattern=r"^menu:about$"),
    ]
