from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.ai.diamond import run_sync, call_ai
from app.ai.prompts.landing_page import get_landing_page_prompt
from app.models.campaign import LandingPage
from app.models.report import Report
from datetime import datetime
import json
import re
import os

landing_bp = Blueprint("landing", __name__, url_prefix="/landing")


@landing_bp.route("/create/<int:report_id>", methods=["GET", "POST"])
@login_required
def create(report_id):
    """Step-by-step landing page creation wizard"""
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("dashboard.index"))

    if request.method == "POST":
        # Initiate AI content generation
        user_preferences = {
            "purpose": request.form.get("purpose", "lead_generation"),
            "tone": request.form.get("tone", "professional"),
            "cta_focus": request.form.get("cta_focus", "get_started"),
            "design_style": request.form.get("design_style", "modern"),
        }

        # Create landing page record
        landing_page = LandingPage(
            user_id=current_user.id,
            report_id=report.id,
            name=f"{report.project_name} Landing Page",
            status="generating",
            user_preferences=user_preferences
        )
        db.session.add(landing_page)
        db.session.commit()

        # Trigger AI generation immediately (synchronous for now)
        try:
            from app.ai.prompts.landing_page import get_landing_page_prompt
            from app.ai.diamond import _parse_json

            # Generate Arabic content
            ar_prompt = get_landing_page_prompt(report.synthesis_result, "ar", user_preferences)
            ar_response = run_sync(call_ai(ar_prompt, model_type="deep"))
            content_ar = _parse_json(ar_response)

            # Generate English content
            en_prompt = get_landing_page_prompt(report.synthesis_result, "en", user_preferences)
            en_response = run_sync(call_ai(en_prompt, model_type="deep"))
            content_en = _parse_json(en_response)

            landing_page.content_ar = content_ar
            landing_page.content_en = content_en
            landing_page.seo_metadata = content_ar.get("seo_metadata", {})
            landing_page.status = "ready"
            landing_page.generation_metadata = {
                "model": "deep",
                "timestamp": datetime.utcnow().isoformat()
            }

            db.session.commit()

            flash("Landing page content generated successfully!", "success")
            return redirect(url_for("landing.edit", landing_page_id=landing_page.id))

        except Exception as e:
            landing_page.status = "error"
            landing_page.generation_metadata = {"error": str(e)}
            db.session.commit()
            flash(f"Failed to generate content: {str(e)}", "error")
            return redirect(url_for("landing.edit", landing_page_id=landing_page.id))

    # GET request - show creation wizard
    return render_template("landing/create.html", report=report)


@landing_bp.route("/edit/<int:landing_page_id>", methods=["GET", "POST"])
@login_required
def edit(landing_page_id):
    """Content editor with live preview"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("landing.index"))

    if request.method == "POST":
        # Handle AJAX content update
        if request.is_json:
            data = request.get_json()
            language = data.get("language", "ar")
            content = data.get("content", {})

            if language == "ar":
                landing_page.content_ar = content
            else:
                landing_page.content_en = content

            landing_page.updated_at = datetime.utcnow()
            db.session.commit()

            return jsonify({"success": True, "message": "Content updated successfully"})

        # Handle form submission
        language = request.form.get("language", "ar")
        content_str = request.form.get("content", "{}")

        try:
            content = json.loads(content_str)

            if language == "ar":
                landing_page.content_ar = content
            else:
                landing_page.content_en = content

            landing_page.updated_at = datetime.utcnow()
            db.session.commit()

            flash("Content updated successfully!", "success")
        except json.JSONDecodeError:
            flash("Invalid content format", "error")

        return redirect(url_for("landing.edit", landing_page_id=landing_page.id))

    return render_template("landing/edit.html", landing_page=landing_page)


@landing_bp.route("/preview/<int:landing_page_id>")
@login_required
def preview(landing_page_id):
    """Live preview of landing page"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        return redirect(url_for("landing.index"))

    language = request.args.get("language", "ar")
    content = landing_page.content_ar if language == "ar" else landing_page.content_en

    return render_template("landing/preview.html",
                         landing_page=landing_page,
                         content=content,
                         language=language)


@landing_bp.route("/publish/<int:landing_page_id>", methods=["POST"])
@login_required
@csrf.exempt  # Exempt from CSRF for AJAX requests
def publish(landing_page_id):
    """Publish landing page"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        return jsonify({"success": False, "error": "Access denied"}), 403

    # Generate slug if needed
    if not landing_page.slug:
        base_slug = re.sub(r'[^a-z0-9]', '-', landing_page.name.lower())[:50]
        # Ensure uniqueness
        counter = 1
        slug = base_slug
        while LandingPage.query.filter_by(slug=slug).first():
            slug = f"{base_slug}-{counter}"
            counter += 1
        landing_page.slug = slug

    landing_page.is_public = True
    landing_page.published_at = datetime.utcnow()
    landing_page.status = "published"
    db.session.commit()

    flash("Landing page published successfully!", "success")

    if request.is_json:
        return jsonify({
            "success": True,
            "url": url_for("landing.view_published", slug=landing_page.slug, _external=True)
        })

    return redirect(url_for("landing.view_published", slug=landing_page.slug))


@landing_bp.route("/<slug>")
def view_published(slug):
    """View published landing page"""
    landing_page = LandingPage.query.filter_by(slug=slug, is_public=True).first_or_404()

    # Detect language from request or default to AR
    language = request.args.get("language", "ar")
    content = landing_page.content_ar if language == "ar" else landing_page.content_en

    # Track analytics
    if landing_page.analytics_data is None:
        landing_page.analytics_data = {"views": 0, "clicks": 0}

    landing_page.analytics_data["views"] = landing_page.analytics_data.get("views", 0) + 1
    db.session.commit()

    return render_template("landing/published/modern_layout.html",
                         landing_page=landing_page,
                         content=content,
                         language=language)


@landing_bp.route("/")
@login_required
def index():
    """List user's landing pages"""
    landing_pages = LandingPage.query.filter_by(
        user_id=current_user.id
    ).order_by(LandingPage.created_at.desc()).all()

    return render_template("landing/index.html", landing_pages=landing_pages)


@landing_bp.route("/upload-hero-image/<int:landing_page_id>", methods=["POST"])
@login_required
def upload_hero_image(landing_page_id):
    """Handle hero image upload for landing pages"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        return jsonify({"success": False, "error": "Access denied"}), 403

    if "image" not in request.files:
        return jsonify({"success": False, "error": "No image file"}), 400

    file = request.files["image"]
    if file.filename == "":
        return jsonify({"success": False, "error": "No file selected"}), 400

    # Validate file type
    allowed_extensions = {"png", "jpg", "jpeg", "gif", "webp"}
    if not ("." in file.filename and file.filename.rsplit(".", 1)[1].lower() in allowed_extensions):
        return jsonify({"success": False, "error": "Invalid file type"}), 400

    # Validate file size (2MB max)
    file.seek(0, os.SEEK_END)
    file_length = file.tell()
    file.seek(0)
    if file_length > 2 * 1024 * 1024:
        return jsonify({"success": False, "error": "File too large (max 2MB)"}), 400

    try:
        # Generate unique filename
        import uuid
        file_extension = file.filename.rsplit(".", 1)[1].lower()
        unique_filename = f"{uuid.uuid4()}.{file_extension}"

        # Create upload directory if it doesn't exist
        upload_dir = os.path.join(current_app.static_folder, "uploads", "landing-pages", str(landing_page.user_id))
        os.makedirs(upload_dir, exist_ok=True)

        # Save file
        file_path = os.path.join(upload_dir, unique_filename)
        file.save(file_path)

        # Update landing page
        landing_page.hero_image_url = f"/static/uploads/landing-pages/{landing_page.user_id}/{unique_filename}"
        landing_page.updated_at = datetime.utcnow()
        db.session.commit()

        current_app.logger.info(f"Hero image uploaded for landing page {landing_page.id}: {unique_filename}")

        return jsonify({
            "success": True,
            "image_url": landing_page.hero_image_url
        })

    except Exception as e:
        current_app.logger.error(f"Hero image upload failed for landing page {landing_page_id}: {str(e)}")
        return jsonify({"success": False, "error": f"Upload failed: {str(e)}"}), 500


@landing_bp.route("/remove-hero-image/<int:landing_page_id>", methods=["POST"])
@login_required
@csrf.exempt
def remove_hero_image(landing_page_id):
    """Remove hero image from landing page"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        return jsonify({"success": False, "error": "Access denied"}), 403

    try:
        # Delete file if exists
        if landing_page.hero_image_url:
            file_path = os.path.join(current_app.static_folder, landing_page.hero_image_url.lstrip("/static/"))
            if os.path.exists(file_path):
                os.remove(file_path)
                current_app.logger.info(f"Deleted hero image for landing page {landing_page.id}: {file_path}")

        # Update landing page
        landing_page.hero_image_url = None
        landing_page.updated_at = datetime.utcnow()
        db.session.commit()

        return jsonify({"success": True})

    except Exception as e:
        current_app.logger.error(f"Hero image removal failed for landing page {landing_page_id}: {str(e)}")
        return jsonify({"success": False, "error": f"Removal failed: {str(e)}"}), 500


@landing_bp.route("/upload-additional-images/<int:landing_page_id>", methods=["POST"])
@login_required
def upload_additional_images(landing_page_id):
    """Handle additional images upload for landing pages"""
    landing_page = LandingPage.query.get_or_404(landing_page_id)
    if landing_page.user_id != current_user.id:
        return jsonify({"success": False, "error": "Access denied"}), 403

    if "images" not in request.files:
        return jsonify({"success": False, "error": "No image files"}), 400

    files = request.files.getlist("images")
    if not files or files[0].filename == "":
        return jsonify({"success": False, "error": "No files selected"}), 400

    # Validate file types
    allowed_extensions = {"png", "jpg", "jpeg", "gif", "webp"}
    uploaded_files = []

    try:
        # Initialize additional_images if None
        if landing_page.additional_images is None:
            landing_page.additional_images = []

        # Create upload directory
        upload_dir = os.path.join(current_app.static_folder, "uploads", "landing-pages", str(landing_page.user_id))
        os.makedirs(upload_dir, exist_ok=True)

        for file in files:
            if file.filename == "":
                continue

            # Validate file type
            if not ("." in file.filename and file.filename.rsplit(".", 1)[1].lower() in allowed_extensions):
                continue

            # Validate file size
            file.seek(0, os.SEEK_END)
            file_length = file.tell()
            file.seek(0)
            if file_length > 2 * 1024 * 1024:
                continue

            # Generate unique filename
            import uuid
            file_extension = file.filename.rsplit(".", 1)[1].lower()
            unique_filename = f"{uuid.uuid4()}.{file_extension}"

            # Save file
            file_path = os.path.join(upload_dir, unique_filename)
            file.save(file_path)

            # Add to landing page
            image_url = f"/static/uploads/landing-pages/{landing_page.user_id}/{unique_filename}"
            landing_page.additional_images.append(image_url)
            uploaded_files.append(image_url)
            current_app.logger.info(f"Additional image uploaded for landing page {landing_page.id}: {unique_filename}")

        landing_page.updated_at = datetime.utcnow()
        db.session.commit()

        return jsonify({
            "success": True,
            "uploaded_files": uploaded_files,
            "total_images": len(landing_page.additional_images)
        })

    except Exception as e:
        current_app.logger.error(f"Additional images upload failed for landing page {landing_page_id}: {str(e)}")
        return jsonify({"success": False, "error": f"Upload failed: {str(e)}"}), 500