"""Support: FAQ + Contact Admin relay + direct @username link."""
from telegram import Update
from telegram.ext import (ContextTypes, ConversationHandler, CallbackQueryHandler,
                          MessageHandler, filters)
from database.db import DB
from utils.keyboards import inline
from utils.decorators import anti_flood, admin_only
from services.notifications import notify_staff
from config import ADMIN_USERNAME

FAQ = (
    "<b>Frequently Asked Questions</b>\n\n"
    "<b>Q:</b> How do I deposit?\n<b>A:</b> 💳 Deposit, pick a method, send funds, "
    "then submit your TX ID/screenshot. Admin will approve.\n\n"
    "<b>Q:</b> How do Telegram Stars work?\n<b>A:</b> Choose ⭐ Telegram Stars, enter the "
    f"quantity, then send the Stars to @{ADMIN_USERNAME}. Your wallet is credited after admin confirms.\n\n"
    "<b>Q:</b> How long does approval take?\n<b>A:</b> Usually a few minutes to a few hours.\n\n"
    "<b>Q:</b> How do I buy a product?\n<b>A:</b> 🛒 Products → category → product → choose quantity → Buy.\n\n"
    "<b>Q:</b> How do referral rewards work?\n<b>A:</b> $0.30 every 15 active referrals, "
    "and $0.80 when a referral makes purchases > $2.00 (once)."
)

AWAIT_MSG = 1

@anti_flood
async def support_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    kb = inline([
        [("💬 Chat in Bot", "sup:contact")],
        [(f"📨 Contact @{ADMIN_USERNAME}", f"https://t.me/{ADMIN_USERNAME}")],
        [("❓ FAQ", "sup:faq")],
        [("⬅ Back", "menu:home")],
    ])
    text = (
        "🎧 <b>Support</b>\n\n"
        "Need help? Chat with an admin right here in the bot, or message "
        f"@{ADMIN_USERNAME} directly on Telegram."
    )
    if update.callback_query:
        await update.callback_query.answer()
        await update.callback_query.edit_message_text(text, parse_mode="HTML", reply_markup=kb)
    else:
        await update.message.reply_html(text, reply_markup=kb)

async def show_faq(update: Update, context: ContextTypes.DEFAULT_TYPE):
    q = update.callback_query; await q.answer()
    await q.edit_message_text(FAQ, parse_mode="HTML",
        reply_markup=inline([[("⬅ Back", "sup:menu")]]))

async def contact_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    q = update.callback_query; await q.answer()
    await q.edit_message_text(
        "✍ Send your message now and an admin will reply here.",
        reply_markup=inline([[("⬅ Cancel", "sup:menu")]]))
    return AWAIT_MSG

async def contact_msg(update: Update, context: ContextTypes.DEFAULT_TYPE):
    u = update.effective_user
    text = update.message.text or update.message.caption or "(non-text message)"
    cur = await DB.execute(
        "INSERT INTO support_messages(user_id, message) VALUES (?, ?)", (u.id, text))
    mid = cur.lastrowid
    await update.message.reply_text(f"✅ Sent. Reference #{mid}")
    await notify_staff(context.bot,
        f"📩 <b>New Support Message</b> #{mid}\n"
        f"From: @{u.username or '—'} (<code>{u.id}</code>)\n"
        f"Name: {u.full_name}\n\n{text[:1000]}\n\n"
        f"Admin reply: <code>/reply {mid} your message</code>")
    return ConversationHandler.END

async def cancel(update, context):
    if update.callback_query:
        await update.callback_query.answer()
        await support_menu(update, context)
    return ConversationHandler.END

def conversation():
    return ConversationHandler(
        entry_points=[
            CallbackQueryHandler(contact_start, pattern=r"^sup:contact$"),
        ],
        states={AWAIT_MSG: [MessageHandler(~filters.COMMAND, contact_msg)]},
        fallbacks=[CallbackQueryHandler(cancel, pattern=r"^sup:menu$")],
        allow_reentry=True, per_message=False,
    )

@admin_only
async def reply_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if len(context.args) < 2:
        await update.message.reply_text("Usage: /reply <ticket_id> <message>"); return
    tid = int(context.args[0])
    msg = " ".join(context.args[1:])
    t = await DB.fetchone("SELECT * FROM support_messages WHERE id=?", (tid,))
    if not t:
        await update.message.reply_text("Ticket not found."); return
    await DB.execute(
        "UPDATE support_messages SET admin_reply=?, status='replied' WHERE id=?", (msg, tid))
    try:
        await context.bot.send_message(
            t["user_id"], f"📩 <b>Admin reply (#{tid})</b>\n\n{msg}", parse_mode="HTML")
        await update.message.reply_text("✅ Reply delivered.")
    except Exception as e:
        await update.message.reply_text(f"⚠ Could not deliver: {e}")
