import time
from telethon import Button

from config import SHOP_NAME, CONTACT_ADMIN
from utils.data_manager import update_user, get_users, get_orders, get_settings

BANNER_URL = "https://api.pentahostinger.id/api/penta1.jpg"
REQUIRED_GROUP = "@pentainfotesti"

_start_time = time.time()


async def is_member(bot, user_id: int) -> bool:
    try:
        member = await bot.get_permissions(REQUIRED_GROUP, user_id)
        return member is not None
    except Exception:
        return False


def build_main_caption():
    users = get_users()
    orders = get_orders()
    total_users = len(users)
    total_orders = len([o for o in orders if o.get("status") == "success"])
    total_pendapatan = sum(o.get("amount", 0) for o in orders if o.get("status") == "success")

    uptime_seconds = int(time.time() - _start_time)
    days = uptime_seconds // 86400
    hours = (uptime_seconds % 86400) // 3600
    minutes = (uptime_seconds % 3600) // 60

    return (
        "<blockquote>🚀 <b>𝐀𝐔𝐓𝐎 𝐎𝐑𝐃𝐄𝐑</b>\n"
        "┃ ʙᴏᴛ ʟᴀʏᴀɴᴀɴ ᴏᴛᴏᴍᴀᴛɪꜱ ʏᴀɴɢ ʙᴇʀᴛᴜɢᴀꜱ\n"
        "┃ ᴍᴇᴍᴘᴇʀᴄᴇᴘᴀᴛ ᴛʀᴀɴꜱᴀᴋꜱɪ ᴅᴇɴɢᴀɴ ʟᴀʏᴀɴᴀɴ\n"
        "┗━━━━━━━━━━━━━━━━━</blockquote>\n\n"
        "<blockquote>⚙️ <b>𝐒𝐈𝐒𝐓𝐄𝐌 𝐅𝐔𝐋𝐋 𝐎𝐓𝐎𝐌𝐀𝐓𝐈𝐒</b>\n"
        "┃ ➥ Auto proses pembayaran\n"
        "┃ ➥ Auto kirim data akun\n"
        "┃ ➥ Online 24/7 nonstop\n"
        "┗━━━━━━━━━━━━━━━━━</blockquote>\n\n"
        "<blockquote>📊 <b>𝐒𝐓𝐀𝐓𝐈𝐒𝐓𝐈𝐊</b>\n"
        f"┃ 🪧 runtime bot : <code>{days}d {hours}h {minutes}m</code>\n"
        f"┃ 👥 total users : <code>{total_users}</code>\n"
        f"┃ 💰 total pendapatan : <code>Rp {total_pendapatan:,}</code>\n"
        f"┃ 🛒 total transaksi : <code>{total_orders}</code>\n"
        "┗━━━━━━━━━━━━━━━━━</blockquote>\n\n"
        "✨ <b>AUTO ORDER BY Penta Hostinger</b>"
    )


def build_main_keyboard():
    return [
        [Button.inline("🛍 Produk", b"menu_produk"), Button.inline("💰 Saldo", b"menu_saldo")],
        [Button.inline("💳 Topup", b"menu_topup"), Button.inline("📖 Panduan", b"menu_panduan")],
        [Button.inline("📞 Kontak Admin", b"menu_kontak"), Button.url("👥 Grup Testi Tele", "https://t.me/pentainfotesti")]
    ]


def build_join_keyboard():
    return [
        [Button.url("👥 Gabung Grup", f"https://t.me/{REQUIRED_GROUP.lstrip('@')}")],
        [Button.inline("✅ Sudah Gabung", b"check_member")]
    ]


async def start(bot, message):
    sender = await message.get_sender()
    update_user(sender.id, {"username": sender.username or "", "name": sender.first_name})

    if not await is_member(bot, sender.id):
        await bot.send_message(
            message.chat_id,
            "⚠️ <b>Akses Ditolak</b>\n\n"
            "Anda belum terdaftar, silahkan gabung ke grup untuk mendaftar.\n\n"
            f"👥 Grup: {REQUIRED_GROUP}",
            parse_mode="html",
            buttons=build_join_keyboard()
        )
        return

    caption = build_main_caption()
    keyboard = build_main_keyboard()

    try:
        await bot.send_file(
            message.chat_id,
            file=BANNER_URL,
            caption=caption,
            parse_mode="html",
            buttons=keyboard
        )
    except Exception:
        await bot.send_message(message.chat_id, caption, parse_mode="html", buttons=keyboard)


async def check_member_callback(bot, event):
    await event.answer()
    if await is_member(bot, event.sender_id):
        caption = build_main_caption()
        keyboard = build_main_keyboard()
        try:
            await event.delete()
        except Exception:
            pass
        try:
            await bot.send_file(
                event.chat_id,
                file=BANNER_URL,
                caption=caption,
                parse_mode="html",
                buttons=keyboard
            )
        except Exception:
            await bot.send_message(event.chat_id, caption, parse_mode="html", buttons=keyboard)
    else:
        await event.answer("❌ Kamu belum gabung grup!", alert=True)


async def show_balance(bot, message):
    from utils.data_manager import get_user
    sender = await message.get_sender()
    user_data = get_user(sender.id)
    balance = user_data.get("balance", 0)
    await bot.send_message(
        message.chat_id,
        f"💰 <b>Saldo Kamu</b>\n\n"
        f"👤 Nama: {sender.first_name}\n"
        f"💵 Saldo: <b>Rp{balance:,}</b>\n\n"
        f"Gunakan /topup untuk menambah saldo.",
        parse_mode="html"
    )


async def show_panduan(bot, message):
    settings = get_settings()
    panduan = settings.get("panduan", "Panduan belum diatur.")
    await bot.send_message(message.chat_id, f"📖 {panduan}", parse_mode="html")


async def show_kontak(bot, message):
    await bot.send_message(
        message.chat_id,
        f"📞 <b>Kontak Admin</b>\n\n"
        f"Untuk pertanyaan, kendala pembayaran, atau laporan masalah:\n\n"
        f"👤 Admin: {CONTACT_ADMIN}\n\n"
        f"Jam operasional: 08.00 - 22.00 WIB",
        parse_mode="html"
    )


async def show_products(bot, message):
    from handlers.shop import categories_keyboard
    await bot.send_message(
        message.chat_id,
        "🛍 <b>Pilih Kategori Produk</b>\n\nSilakan pilih kategori:",
        parse_mode="html",
        buttons=categories_keyboard()
    )


async def show_topup(bot, message):
    from handlers.callback import topup_keyboard
    await bot.send_message(
        message.chat_id,
        "💳 <b>Topup Saldo</b>\n\nPilih nominal topup:",
        parse_mode="html",
        buttons=topup_keyboard()
    )