import logging
import os
import html

from telegram import (
    Update,
    InlineKeyboardButton,
    InlineKeyboardMarkup
)

from telegram.ext import ContextTypes

from services.auth_service import is_admin, is_owner
from services.maintenance_service import get_maintenance
from services.vip_service import get_package_by_id

log = logging.getLogger("bot.photo")


def _format_rupiah(value):
    try:
        if isinstance(value, str):
            value = value.replace(".", "").replace(",", "").strip()
        return f"Rp {int(value):,}".replace(",", ".")
    except (TypeError, ValueError):
        return "-"


def _payment_summary(context, is_vs=False):
    if is_vs:
        package_label = f"VCS - {context.user_data.get('vs_paket', '-')}"
        total = context.user_data.get("vs_harga_bayar", 0)
        confirm_label = "✅ Kirim ke Talent"
        confirm_callback = "konfirmasi_vs"
    else:
        paket_type = context.user_data.get("paket_type", "single")
        selected_ids = context.user_data.get("vip_selected_ids", [])
        if paket_type == "single" and selected_ids:
            pkg = get_package_by_id(selected_ids[0])
            package_label = pkg["nama"] if pkg else "Paket VIP"
        elif paket_type == "take_several":
            package_label = f"Take Beberapa ({len(selected_ids)} Paket)"
        elif paket_type == "take_all":
            package_label = "Take All"
        else:
            package_label = "Paket VIP"
        total = context.user_data.get("vip_harga_bayar", 0)
        confirm_label = "✅ Kirim ke Admin"
        confirm_callback = "konfirmasi"

    transaction_code = context.user_data.get("transaction_code", "-")
    text = (
        "📸 <b>Bukti pembayaran diterima.</b>\n\n"
        f"Paket: <b>{html.escape(str(package_label))}</b>\n"
        f"Total: <b>{_format_rupiah(total)}</b>\n"
        f"Kode: <code>{html.escape(str(transaction_code))}</code>\n\n"
        "Pastikan foto sudah benar sebelum dikirim."
    )
    keyboard = InlineKeyboardMarkup([
        [InlineKeyboardButton(confirm_label, callback_data=confirm_callback)],
        [InlineKeyboardButton("🔄 Ganti Foto", callback_data="ganti_bukti")],
        [InlineKeyboardButton("❌ Batalkan", callback_data="batal_transaksi")],
    ])
    return text, keyboard


async def handle_photo(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    user = update.effective_user

    if get_maintenance() and not is_owner(user.id):
        await update.message.reply_text(
            "🔧 <b>Bot sedang dalam maintenance.</b>\n\n"
            "Mohon bersabar, bot akan segera aktif kembali. Terima kasih! 🙏",
            parse_mode="HTML"
        )
        return

    # =========================
    # SKIP JIKA ADMIN SEDANG BROADCAST
    # =========================

    if (
        is_admin(update.effective_user.id)
        and context.user_data.get("broadcast_step") == "waiting_media"
    ):
        from handlers.broadcast_handler import handle_broadcast_media
        await handle_broadcast_media(update, context)
        return
    
    # =========================
    # OWNER SET BANNER
    # =========================

    if context.user_data.get("waiting_vip_edit_banner") and is_owner(update.effective_user.id):
        from services.vip_service import set_package_banner

        photo = update.message.photo[-1]
        pkg_id = context.user_data.pop("editing_vip_id", None)
        context.user_data.pop("waiting_vip_edit_banner", None)
        if not pkg_id:
            await update.message.reply_text("❌ Paket tidak ditemukan.")
            return

        pkg = set_package_banner(pkg_id, photo.file_id)
        if not pkg:
            await update.message.reply_text("❌ Paket tidak ditemukan.")
            return

        if context.user_data.get("vip_add_flow"):
            context.user_data["editing_vip_id"] = pkg_id
            context.user_data["waiting_vip_edit_caption"] = True
            await update.message.reply_text(
                f"✅ Banner paket <b>{pkg['nama']}</b> berhasil diset!\n\n"
                "Sekarang kirim <b>caption</b> untuk paket ini.\n\n"
                "<code>{nama}</code> dan <code>{harga}</code> sudah otomatis ditambahkan.\n"
                "Cukup tulis teks body caption.\n"
                "Emoji premium bisa langsung ditempel di caption.\n"
                "Untuk blockquote, gunakan tag HTML <code>&lt;blockquote expandable&gt;</code>.",
                parse_mode="HTML",
            )
        else:
            await update.message.reply_text(
                f"✅ Banner paket <b>{pkg['nama']}</b> berhasil diperbarui.",
                parse_mode="HTML",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton("✏️ Lanjut Edit", callback_data=f"owner_vip_edit_detail_{pkg_id}")
                ]])
            )
        return

    if context.user_data.get("waiting_banner") and is_admin(update.effective_user.id):
        from services.payment_info_service import set_banner
        photo = update.message.photo[-1]
        set_banner(photo.file_id)
        context.user_data.pop("waiting_banner", None)
        await update.message.reply_text(
            "✅ Banner berhasil diperbarui.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_group_settings")
            ]])
        )
        return

    # =========================
    # OWNER SET FOTO QRIS
    # =========================

    if context.user_data.get("waiting_qris") and is_admin(update.effective_user.id):
        from services.payment_info_service import set_qris as save_qris
        photo = update.message.photo[-1]
        save_qris(photo.file_id)
        context.user_data.pop("waiting_qris", None)
        await update.message.reply_text(
            "✅ Gambar QRIS berhasil diperbarui.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="owner_payment_menu")
            ]])
        )
        return

    # =========================
    # ADMIN UBAH FOTO VS
    # =========================

    if context.user_data.get("vs_waiting_image"):

        photo = update.message.photo[-1]

        from services.vs_service import set_vs_image

        target_admin = context.user_data.get(
            "vs_target_admin",
            update.effective_user.id
        )

        set_vs_image(
            target_admin,
            photo.file_id
        )

        context.user_data.pop("vs_waiting_image", None)

        await update.message.reply_text(
            "✅ Foto katalog VS berhasil diperbarui.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("⬅️ Kembali", callback_data="vs_manage")
            ]])
        )

        return

    # =========================
    # REJOIN - BUKTI APPROVE ADMIN
    # =========================

    if context.user_data.get("rejoin_step") == "waiting_approval":
        from config import OWNERS
        from data.memory import REJOIN_PENDING
        from datetime import datetime

        user = update.effective_user
        photo = update.message.photo[-1]
        context.user_data["rejoin_step"] = "done"

        selected_pkgs = list(context.user_data.get("rejoin_selected_pkgs", set()))

        REJOIN_PENDING[user.id] = {
            "photo_id": photo.file_id,
            "first_name": user.first_name,
            "username": user.username or "-",
            "selected_pkgs": selected_pkgs,
            "owner_selected_pkgs": []
        }

        # Send simple notification with "Buka Rejoin" button to owners
        notif_text = (
            f"🔄 <b>Permintaan Rejoin Baru!</b>\n\n"
            f"Cek menu <b>Notifications</b> → <b>Rejoin Requests</b> untuk melihat detail."
        )
        keyboard_owner = InlineKeyboardMarkup([
            [InlineKeyboardButton("🔄 Buka Rejoin Request", callback_data="owner_notifications")]
        ])

        for owner_id in OWNERS:
            try:
                await context.bot.send_message(
                    chat_id=owner_id,
                    text=notif_text,
                    parse_mode="HTML",
                    reply_markup=keyboard_owner
                )
            except Exception as e:
                log.error("[REJOIN] Gagal kirim notif ke owner %s: %s", owner_id, e)

        caption = (
            "✅ <b>Bukti diterima!</b>\n\n"
            "⏳ Sedang diproses, harap tunggu konfirmasi dari owner."
        )
        banner_path = "assets/banner_rejoin.jpg"
        if os.path.exists(banner_path):
            await update.message.reply_photo(
                photo=open(banner_path, "rb"),
                caption=caption,
                parse_mode="HTML"
            )
        else:
            await update.message.reply_text(caption, parse_mode="HTML")
        return

    # =========================
    # VALIDASI TRANSAKSI USER
    # =========================

    is_vip = context.user_data.get("status_transaksi") == "pending"
    is_vs = context.user_data.get("vs_status") == "waiting_payment"

    log.info(
        "[FOTO] User %s kirim foto | is_vip=%s | is_vs=%s",
        update.effective_user.id, is_vip, is_vs
    )

    if not is_vip and not is_vs:
        log.warning("[FOTO] User %s kirim foto tapi tidak dalam transaksi aktif.", update.effective_user.id)
        await update.message.reply_text(
            "❌ Kamu belum memilih paket VIP atau transaksi sudah selesai.\n"
            "Silakan klik /start dan pilih paket terlebih dahulu."
        )

        return

    if not context.user_data.get("payment_method"):
        await update.message.reply_text(
            "💳 Pilih metode pembayaran dulu pada pesan sebelumnya.\n"
            "Setelah invoice muncul dan pembayaran dilakukan, kirim foto bukti pembayaran."
        )
        return
    
    

    # =========================
    # CEGAH DOUBLE UPLOAD
    # =========================

    if context.user_data.get("bukti_dikirim"):
        log.warning("[FOTO] User %s sudah pernah kirim bukti sebelumnya.", update.effective_user.id)
        confirm_label = "✅ Kirim ke Talent" if is_vs else "✅ Kirim ke Admin"
        confirm_callback = "konfirmasi_vs" if is_vs else "konfirmasi"
        await update.message.reply_text(
            "⚠️ Kamu sudah mengirimkan bukti foto untuk pesanan ini!\n"
            "Kalau foto sebelumnya salah, klik <b>Ganti Foto</b>.",
            parse_mode="HTML",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton(confirm_label, callback_data=confirm_callback)],
                [InlineKeyboardButton("🔄 Ganti Foto", callback_data="ganti_bukti")],
                [InlineKeyboardButton("❌ Batalkan", callback_data="batal_transaksi")],
            ])
        )

        return

    # =========================
    # SIMPAN FOTO
    # =========================

    photo = update.message.photo[-1]

    context.user_data["bukti"] = photo.file_id
    context.user_data["bukti_dikirim"] = True
    log.info("[FOTO] Bukti foto user %s disimpan: %s", update.effective_user.id, photo.file_id)

    if is_vs:
        text, keyboard = _payment_summary(context, is_vs=True)
        await update.message.reply_text(text, parse_mode="HTML", reply_markup=keyboard)
        return

    # FLOW VIP BIASA
    text, keyboard = _payment_summary(context)
    await update.message.reply_text(text, parse_mode="HTML", reply_markup=keyboard)
