import stripe
from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app, jsonify
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.models.subscription import Plan, Subscription

billing_bp = Blueprint("billing", __name__, url_prefix="/billing")


@billing_bp.route("/plans")
@login_required
def plans():
    all_plans = Plan.query.order_by(Plan.price_monthly).all()
    return render_template("billing/plans.html", plans=all_plans)


@billing_bp.route("/checkout/<int:plan_id>", methods=["POST"])
@login_required
def checkout(plan_id):
    plan = Plan.query.get_or_404(plan_id)
    if not plan.stripe_price_id:
        flash("This plan does not support online checkout.", "error")
        return redirect(url_for("billing.plans"))

    stripe.api_key = current_app.config["STRIPE_SECRET_KEY"]

    try:
        session = stripe.checkout.Session.create(
            payment_method_types=["card"],
            line_items=[{"price": plan.stripe_price_id, "quantity": 1}],
            mode="subscription",
            success_url=url_for("billing.success", _external=True) + "?session_id={CHECKOUT_SESSION_ID}",
            cancel_url=url_for("billing.plans", _external=True),
            client_reference_id=str(current_user.id),
            metadata={"plan_id": str(plan.id)},
        )
        return redirect(session.url, code=303)
    except Exception as e:
        flash(f"Payment error: {e}", "error")
        return redirect(url_for("billing.plans"))


@billing_bp.route("/success")
@login_required
def success():
    flash("Subscription activated successfully!", "success")
    return redirect(url_for("dashboard.index"))


@billing_bp.route("/webhook", methods=["POST"])
@csrf.exempt
def webhook():
    payload = request.get_data()
    sig_header = request.headers.get("Stripe-Signature")
    stripe.api_key = current_app.config["STRIPE_SECRET_KEY"]

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, current_app.config["STRIPE_WEBHOOK_SECRET"]
        )
    except Exception:
        return jsonify({"error": "Invalid signature"}), 400

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        metadata = session.get("metadata", {})

        # ── Marketplace one-time purchase ──
        if metadata.get("type") == "marketplace":
            from app.models.features import MarketplaceListing, MarketplacePurchase, Notification
            listing_id = int(metadata.get("listing_id", 0))
            buyer_id = int(metadata.get("buyer_id", 0))
            if listing_id and buyer_id:
                purchase = MarketplacePurchase.query.filter_by(
                    stripe_session_id=session["id"]
                ).first()
                if purchase and purchase.status == "pending":
                    purchase.status = "completed"
                    purchase.stripe_payment_intent = session.get("payment_intent")
                    purchase.listing.purchases += 1
                    # Notify seller
                    seller_notif = Notification(
                        user_id=purchase.listing.user_id,
                        title="تم بيع دراستك! 🎉",
                        message=f"اشترى أحد المستخدمين دراسة «{purchase.listing.title}» بمبلغ {purchase.amount} {purchase.currency}.",
                        category="marketplace",
                    )
                    buyer_notif = Notification(
                        user_id=buyer_id,
                        title="تم الشراء بنجاح ✅",
                        message=f"يمكنك الآن عرض دراسة «{purchase.listing.title}» بالكامل.",
                        category="marketplace",
                    )
                    db.session.add_all([seller_notif, buyer_notif])
                    db.session.commit()
        else:
            # ── Subscription checkout ──
            user_id = int(session.get("client_reference_id", 0))
            plan_id = int(metadata.get("plan_id", 0))
            if user_id and plan_id:
                sub = Subscription.query.filter_by(user_id=user_id).first()
                if sub:
                    sub.plan_id = plan_id
                    sub.stripe_subscription_id = session.get("subscription")
                    sub.stripe_customer_id = session.get("customer")
                    sub.status = "active"
                else:
                    sub = Subscription(
                        user_id=user_id, plan_id=plan_id,
                        stripe_subscription_id=session.get("subscription"),
                        stripe_customer_id=session.get("customer"),
                        status="active",
                    )
                    db.session.add(sub)
                db.session.commit()

    elif event["type"] == "customer.subscription.deleted":
        sub_id = event["data"]["object"]["id"]
        sub = Subscription.query.filter_by(stripe_subscription_id=sub_id).first()
        if sub:
            sub.status = "canceled"
            db.session.commit()

    return jsonify({"status": "ok"})


@billing_bp.route("/manage")
@login_required
def manage():
    if not current_user.subscription or not current_user.subscription.stripe_customer_id:
        return redirect(url_for("billing.plans"))

    stripe.api_key = current_app.config["STRIPE_SECRET_KEY"]
    try:
        session = stripe.billing_portal.Session.create(
            customer=current_user.subscription.stripe_customer_id,
            return_url=url_for("dashboard.index", _external=True),
        )
        return redirect(session.url, code=303)
    except Exception as e:
        flash(f"Error: {e}", "error")
        return redirect(url_for("dashboard.index"))
