import uuid
from datetime import datetime
from telethon import Button

from config import MIN_TOPUP
from utils.data_manager import add_order, get_order_by_id, add_balance, update_order, get_user
from utils.notif import send_notif_topup
from api import create_qris_payment, check_qris_payment


def build_topup_text(amount: int, order_id: str) -> str:
    return (
        f"💳 **Topup via QRIS**\n\n"
        f"💰 Nominal: **Rp{amount:,}**\n"
        f"🔖 Order ID: `{order_id}`\n\n"
        f"Scan QRIS lalu klik **Cek Status Pembayaran**."
    )


def build_topup_markup(order_id: str):
    return [[
        Button.inline("🔄 Cek Status", f"cektopup_{order_id}".encode()),
        Button.inline("❌ Batal", b"back_main")
    ]]


async def process_topup_qris(bot, event, amount: int):
    if amount < MIN_TOPUP:
        await event.edit(f"❌ Minimal topup Rp{MIN_TOPUP:,}")
        return

    await event.edit("⏳ Membuat QRIS, mohon tunggu...")

    sender = await event.get_sender()
    result = create_qris_payment(
        amount,
        product_name="Topup Saldo",
        customer_name=sender.first_name,
        customer_id=sender.username or str(sender.id)
    )

    if result.get("status") == "error":
        await event.edit(f"❌ Gagal membuat pembayaran: {result.get('message')}")
        return

    order_id = result.get("order_id")
    qris_url = result.get("qr_code_url") or result.get("qr_code_url_v2", "")

    add_order({
        "order_id": order_id,
        "user_id": sender.id,
        "type": "topup",
        "amount": amount,
        "method": "qris",
        "status": "pending",
        "created_at": datetime.now().isoformat()
    })

    text = build_topup_text(amount, order_id)
    markup = build_topup_markup(order_id)

    if qris_url:
        try:
            await bot.send_file(sender.id, file=qris_url, caption=text, buttons=markup)
            await event.delete()
        except Exception:
            await event.edit(text + f"\n\n{qris_url}", buttons=markup)
    else:
        await event.edit(text, buttons=markup)


async def handle_cektopup(bot, event, order_id: str):
    order = get_order_by_id(order_id)
    if not order:
        await event.answer("Order tidak ditemukan.", alert=True)
        return
    if order["status"] == "success":
        await event.answer("✅ Sudah dikonfirmasi sebelumnya.", alert=True)
        return

    result = check_qris_payment(order_id)
    payment_status = result.get("order_data", {}).get("transaction_status", "") or result.get("status", "")

    if payment_status in ("paid", "success", "settlement", "capture"):
        add_balance(order["user_id"], order["amount"])
        update_order(order_id, {"status": "success"})
        await send_notif_topup(bot, {
            "order_id": order_id,
            "user_id": order["user_id"],
            "amount": order["amount"],
            "created_at": datetime.now().isoformat()
        })
        user_data = get_user(order["user_id"])
        try:
            await event.delete()
        except Exception:
            pass
        await bot.send_message(
            order["user_id"],
            f"✅ **Topup Berhasil!**\n\n"
            f"💰 Topup: Rp{order['amount']:,}\n"
            f"💵 Saldo sekarang: Rp{user_data['balance']:,}"
        )
    else:
        await event.answer("⏳ Pembayaran belum diterima.", alert=True)


async def handle_topup_message(bot, message, user_data_store: dict):
    sender = await message.get_sender()
    user_data_store[sender.id]["awaiting_topup"] = False
    text = message.text

    try:
        amount = int(text.replace(".", "").replace(",", "").strip())
        if amount < MIN_TOPUP:
            await message.reply(f"❌ Minimal topup Rp{MIN_TOPUP:,}")
            return

        await message.reply("⏳ Membuat QRIS, mohon tunggu...")

        result = create_qris_payment(
            amount,
            product_name="Topup Saldo",
            customer_name=sender.first_name,
            customer_id=sender.username or str(sender.id)
        )

        if result.get("status") == "error":
            await message.reply(f"❌ {result.get('message')}")
            return

        order_id = result.get("order_id")
        qris_url = result.get("qr_code_url") or result.get("qr_code_url_v2", "")

        add_order({
            "order_id": order_id,
            "user_id": sender.id,
            "type": "topup",
            "amount": amount,
            "method": "qris",
            "status": "pending",
            "created_at": datetime.now().isoformat()
        })

        msg_text = build_topup_text(amount, order_id)
        markup = build_topup_markup(order_id)

        if qris_url:
            await bot.send_file(sender.id, file=qris_url, caption=msg_text, buttons=markup)
        else:
            await message.reply(msg_text, buttons=markup)

    except ValueError:
        await message.reply("❌ Masukkan angka yang valid. Contoh: 50000")