from flask import Blueprint, flash, redirect, render_template, request, session, url_for
from services.cart_service import get_or_create_cart
from services.garage_service import get_customer_dispatch_requests, get_customer_garage_holds
from utils.db import get_db, transaction
from utils.formatting import format_inr, parse_json_safe, strip_model_codes_for_card
from utils.security import (
    check_rate_limit,
    csrf_protect,
    customer_login_required,
    get_current_customer,
    hash_password,
    verify_password,
)

customer_bp = Blueprint("customer", __name__)


def _safe_next_url(raw_next: str | None, fallback: str = "/account") -> str:
    if raw_next and raw_next.startswith("/") and not raw_next.startswith("//"):
        return raw_next
    return fallback


@customer_bp.route("/register", methods=["GET", "POST"])
@csrf_protect
def register():
    if get_current_customer():
        return redirect(url_for("customer.account"))

    if request.method == "POST":
        if not check_rate_limit("cust_register", 15, 300):
            flash("Too many registration attempts. Please wait a few minutes.", "error")
            return render_template("register.html"), 429

        full_name = (request.form.get("full_name") or "").strip()
        email = (request.form.get("email") or "").strip().lower()
        phone = "".join(ch for ch in (request.form.get("phone") or "") if ch.isdigit())
        password = request.form.get("password") or ""
        confirm = request.form.get("confirm_password") or ""

        if not full_name or not email or "@" not in email:
            flash("Please provide your full name and a valid email address.", "error")
            return render_template("register.html"), 400
        if len(phone) < 10:
            flash("Please enter a valid 10-digit mobile number.", "error")
            return render_template("register.html"), 400
        if len(password) < 8:
            flash("Password must be at least 8 characters long.", "error")
            return render_template("register.html"), 400
        if password != confirm:
            flash("Passwords do not match.", "error")
            return render_template("register.html"), 400

        db = get_db()
        existing = db.execute("SELECT id FROM customer_users WHERE email = ? COLLATE NOCASE", (email,)).fetchone()
        if existing:
            flash("An account with this email already exists. Please sign in.", "error")
            return render_template("register.html"), 400

        with transaction(db) as conn:
            cur = conn.execute(
                "INSERT INTO customer_users (email, password_hash, is_active) VALUES (?, ?, 1)",
                (email, hash_password(password)),
            )
            cust_id = cur.lastrowid
            conn.execute(
                """
                INSERT INTO customer_profiles (customer_id, full_name, phone, whatsapp_phone)
                VALUES (?, ?, ?, ?)
                """,
                (cust_id, full_name, phone, phone),
            )
        session["customer_id"] = cust_id
        get_or_create_cart(cust_id)
        flash("Welcome to Diecast World India! Your collector account is ready.", "success")
        return redirect(_safe_next_url(request.form.get("next") or request.args.get("next")))

    return render_template("register.html", next_url=request.args.get("next", "/account"))


@customer_bp.route("/login", methods=["GET", "POST"])
@csrf_protect
def login():
    if get_current_customer():
        return redirect(url_for("customer.account"))

    if request.method == "POST":
        if not check_rate_limit("cust_login", 20, 300):
            flash("Too many login attempts. Please wait a few minutes.", "error")
            return render_template("login.html"), 429

        email = (request.form.get("email") or "").strip().lower()
        password = request.form.get("password") or ""
        db = get_db()
        user = db.execute(
            "SELECT * FROM customer_users WHERE email = ? COLLATE NOCASE",
            (email,),
        ).fetchone()

        if not user:
            msg = "No account found for this email. Please register first before signing in."
            flash(msg, "error")
            return render_template(
                "login.html",
                next_url=request.form.get("next", "/account"),
                prefill_email=email,
                unregistered_alert=msg,
            ), 401

        if not user["is_active"]:
            flash("Your account has been disabled by the store administrator. Please contact support.", "error")
            return render_template(
                "login.html",
                next_url=request.form.get("next", "/account"),
                prefill_email=email,
            ), 403

        if not verify_password(user["password_hash"], password):
            flash("Invalid email or password.", "error")
            return render_template(
                "login.html",
                next_url=request.form.get("next", "/account"),
                prefill_email=email,
            ), 401

        db.execute("UPDATE customer_users SET last_login_at = datetime('now') WHERE id = ?", (user["id"],))
        db.commit()
        session["customer_id"] = user["id"]
        get_or_create_cart(user["id"])
        flash("Signed in successfully.", "success")
        return redirect(_safe_next_url(request.form.get("next") or request.args.get("next")))

    return render_template("login.html", next_url=request.args.get("next", "/account"))


@customer_bp.route("/logout", methods=["POST"])
@csrf_protect
def logout():
    session.pop("customer_id", None)
    flash("You have been signed out.", "success")
    return redirect(url_for("storefront.index"))


@customer_bp.route("/account")
@customer_login_required
def account():
    cust = get_current_customer()
    db = get_db()

    addresses = [
        dict(r)
        for r in db.execute(
            "SELECT * FROM addresses WHERE customer_id = ? ORDER BY is_default DESC, id DESC",
            (cust["id"],),
        ).fetchall()
    ]

    order_rows = db.execute(
        """
        SELECT o.*, p.status AS payment_status, p.utr_number, p.payment_method,
               s.courier_name, s.tracking_number, s.tracking_url
        FROM orders o
        LEFT JOIN payments p ON p.id = (SELECT id FROM payments WHERE order_id = o.id ORDER BY id DESC LIMIT 1)
        LEFT JOIN shipping s ON s.order_id = o.id
        WHERE o.customer_id = ?
        ORDER BY o.id DESC
        """,
        (cust["id"],),
    ).fetchall()
    orders = []
    for r in order_rows:
        d = dict(r)
        d["total_formatted"] = format_inr(d["total_paise"])
        orders.append(d)

    payment_rows = db.execute(
        """
        SELECT pay.*, o.order_number, o.status AS order_status
        FROM payments pay
        JOIN orders o ON o.id = pay.order_id
        WHERE o.customer_id = ?
        ORDER BY pay.id DESC
        """,
        (cust["id"],),
    ).fetchall()
    payments = []
    for r in payment_rows:
        d = dict(r)
        d["amount_formatted"] = format_inr(d["amount_paise"])
        payments.append(d)

    garage_holds = get_customer_garage_holds(cust["id"])
    dispatch_requests = get_customer_dispatch_requests(cust["id"])

    po_rows = db.execute(
        """
        SELECT po.*, o.order_number, o.tracking_token
        FROM pre_orders po
        JOIN orders o ON o.id = po.order_id
        WHERE po.customer_id = ?
        ORDER BY po.id DESC
        """,
        (cust["id"],),
    ).fetchall()
    preorders = []
    for r in po_rows:
        d = dict(r)
        d["token_formatted"] = format_inr(d["total_token_paise"])
        d["balance_formatted"] = format_inr(d["total_balance_paise"])
        items = db.execute(
            """
            SELECT poi.*, pr.name AS product_name, pr.sku, pr.scale
            FROM pre_order_items poi
            JOIN products pr ON pr.id = poi.product_id
            WHERE poi.pre_order_id = ?
            """,
            (r["id"],),
        ).fetchall()
        d["items"] = [dict(i) for i in items]
        preorders.append(d)

    wish_rows = db.execute(
        """
        SELECT p.id, p.sku, p.slug, p.name, p.scale, p.price_paise, p.mrp_paise,
               p.specifications_json, p.is_pre_order, p.pre_order_token_paise,
               b.name AS brand_name,
               COALESCE(
                   (SELECT image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.sort_order ASC LIMIT 1),
                   '/static/assets/images/logo.png'
               ) AS image_url
        FROM wishlist w
        JOIN products p ON p.id = w.product_id
        JOIN brands b ON b.id = p.brand_id
        WHERE w.customer_id = ? AND p.is_visible = 1
        ORDER BY w.id DESC
        """,
        (cust["id"],),
    ).fetchall()
    wishlist_items = []
    wish_ids = [int(r["id"]) for r in wish_rows]
    wish_img_map: dict[int, list[str]] = {}
    if wish_ids:
        ph = ",".join("?" for _ in wish_ids)
        for ir in db.execute(
            f"SELECT product_id, image_url FROM product_images WHERE product_id IN ({ph}) ORDER BY product_id ASC, is_primary DESC, sort_order ASC, id ASC",
            wish_ids,
        ).fetchall():
            wish_img_map.setdefault(int(ir["product_id"]), []).append(ir["image_url"])
    for r in wish_rows:
        d = dict(r)
        specs = parse_json_safe(d.get("specifications_json"), {})
        d["price_formatted"] = format_inr(d["price_paise"])
        d["card_title"] = strip_model_codes_for_card(d["name"]) or d["name"]
        d["chassis"] = specs.get("chassis", "Diecast Metal")
        urls = wish_img_map.get(int(d["id"])) or [d["image_url"]]
        d["image_urls"] = urls
        wishlist_items.append(d)

    return render_template(
        "account.html",
        customer=cust,
        addresses=addresses,
        orders=orders,
        payments=payments,
        garage_holds=garage_holds,
        dispatch_requests=dispatch_requests,
        preorders=preorders,
        wishlist_items=wishlist_items,
    )


@customer_bp.route("/account/profile", methods=["POST"])
@customer_login_required
@csrf_protect
def update_profile():
    cust = get_current_customer()
    full_name = (request.form.get("full_name") or "").strip()
    phone = "".join(ch for ch in (request.form.get("phone") or "") if ch.isdigit())
    whatsapp_phone = "".join(ch for ch in (request.form.get("whatsapp_phone") or phone) if ch.isdigit())
    if not full_name or len(phone) < 10:
        flash("Valid full name and 10-digit phone number are required.", "error")
        return redirect(url_for("customer.account"))

    db = get_db()
    db.execute(
        """
        UPDATE customer_profiles
        SET full_name = ?, phone = ?, whatsapp_phone = ?, updated_at = datetime('now')
        WHERE customer_id = ?
        """,
        (full_name, phone, whatsapp_phone, cust["id"]),
    )
    db.commit()
    flash("Profile updated.", "success")
    return redirect(url_for("customer.account"))


@customer_bp.route("/account/addresses", methods=["POST"])
@customer_login_required
@csrf_protect
def add_address():
    cust = get_current_customer()
    label = (request.form.get("label") or "Home").strip()
    recipient_name = (request.form.get("recipient_name") or cust["full_name"]).strip()
    phone = "".join(ch for ch in (request.form.get("phone") or cust["phone"]) if ch.isdigit())
    line1 = (request.form.get("address_line1") or "").strip()
    line2 = (request.form.get("address_line2") or "").strip()
    city = (request.form.get("city") or "").strip()
    state = (request.form.get("state") or "").strip()
    pincode = (request.form.get("pincode") or "").strip()
    is_default = 1 if request.form.get("is_default") == "1" else 0

    if not recipient_name or len(phone) < 10 or not line1 or not city or not pincode:
        flash("Please complete all required address fields.", "error")
        return redirect(url_for("customer.account"))

    with transaction() as conn:
        if is_default:
            conn.execute("UPDATE addresses SET is_default = 0 WHERE customer_id = ?", (cust["id"],))
        conn.execute(
            """
            INSERT INTO addresses (
                customer_id, label, recipient_name, phone, address_line1, address_line2, city, state, pincode, is_default
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (cust["id"], label, recipient_name, phone, line1, line2, city, state, pincode, is_default),
        )
    flash("Saved new delivery address.", "success")
    return redirect(url_for("customer.account"))


@customer_bp.route("/account/addresses/<int:address_id>/delete", methods=["POST"])
@customer_login_required
@csrf_protect
def delete_address(address_id: int):
    cust = get_current_customer()
    db = get_db()
    db.execute("DELETE FROM addresses WHERE id = ? AND customer_id = ?", (address_id, cust["id"]))
    db.commit()
    flash("Address removed.", "success")
    return redirect(url_for("customer.account"))


@customer_bp.route("/account/addresses/<int:address_id>/default", methods=["POST"])
@customer_login_required
@csrf_protect
def set_default_address(address_id: int):
    cust = get_current_customer()
    with transaction() as conn:
        row = conn.execute(
            "SELECT id FROM addresses WHERE id = ? AND customer_id = ?",
            (address_id, cust["id"]),
        ).fetchone()
        if not row:
            flash("Address not found.", "error")
            return redirect(url_for("customer.account"))
        conn.execute("UPDATE addresses SET is_default = 0 WHERE customer_id = ?", (cust["id"],))
        conn.execute("UPDATE addresses SET is_default = 1 WHERE id = ? AND customer_id = ?", (address_id, cust["id"]))
    flash("Default address updated.", "success")
    return redirect(url_for("customer.account"))
