"""SaaS Public Blueprint.

Handles SaaS marketing landing page, pricing comparison,
self-serve NGO registration and onboarding wizard, and public NGO directory.
"""

from datetime import datetime, timezone, timedelta
import re
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_user, current_user
from werkzeug.security import generate_password_hash

from app.extensions import db, limiter
from app.models.subscription_plan import SubscriptionPlan
from app.models.organization import Organization, TenantSubscription
from app.models.user import User
from app.models.role import Role
from app.models.programme_pillar import ProgrammePillar


saas_bp = Blueprint('saas', __name__, url_prefix='/saas')


def _slugify(text: str) -> str:
    """Generates a clean URL slug from organization name."""
    text = (text or '').strip().lower()
    text = re.sub(r'[^a-z0-9]+', '-', text)
    return text.strip('-') or 'ngo-hub'


@saas_bp.route('/', endpoint='landing')
@saas_bp.route('/welcome')
def landing():
    """
    Renders the SaaS Platform marketing landing page with features,
    statistics, and pricing plans.
    """
    plans = SubscriptionPlan.query.filter_by(is_active=True).order_by(SubscriptionPlan.price_monthly.asc()).all()
    org_count = Organization.query.filter_by(status='active').count()
    
    return render_template('saas/landing.html', plans=plans, org_count=org_count)


@saas_bp.route('/plans', endpoint='plans')
def plans():
    """
    Renders dedicated SaaS Pricing and Plan comparison matrix.
    """
    all_plans = SubscriptionPlan.query.filter_by(is_active=True).order_by(SubscriptionPlan.price_monthly.asc()).all()
    return render_template('saas/plans.html', plans=all_plans)


@saas_bp.route('/register', methods=['GET', 'POST'], endpoint='register_ngo')
@limiter.limit('10 per hour', methods=['POST'])
def register_ngo():
    """
    Self-Serve NGO Onboarding & Workspace Registration Wizard.
    Provisions a new tenant Organization, links subscription plan,
    creates the tenant Admin account, and establishes instant login.
    """
    if current_user.is_authenticated and not getattr(current_user, 'is_superadmin', False):
        return redirect(url_for('portals.dashboard'))

    plans = SubscriptionPlan.query.filter_by(is_active=True).order_by(SubscriptionPlan.price_monthly.asc()).all()
    selected_plan_slug = request.args.get('plan', 'starter')

    if request.method == 'POST':
        org_name = request.form.get('org_name', '').strip()
        org_slug = _slugify(request.form.get('org_slug', '') or org_name)
        reg_number = request.form.get('reg_number', '').strip()
        tagline = request.form.get('tagline', '').strip()
        org_email = request.form.get('org_email', '').strip().lower()
        org_phone = request.form.get('org_phone', '').strip()
        address = request.form.get('address', '').strip()
        plan_id = request.form.get('plan_id')
        
        # Admin account details
        admin_name = request.form.get('admin_name', '').strip()
        admin_email = request.form.get('admin_email', '').strip().lower()
        password = request.form.get('password', '')
        confirm_password = request.form.get('confirm_password', '')

        # Validations
        errors = []
        if not org_name or len(org_name) < 3:
            errors.append('Organization name must be at least 3 characters.')
        if not org_email or '@' not in org_email:
            errors.append('Valid organization email is required.')
        if not admin_name:
            errors.append('Admin full name is required.')
        if not admin_email or '@' not in admin_email:
            errors.append('Valid administrator email is required.')
        if not password or len(password) < 8:
            errors.append('Password must be at least 8 characters long.')
        if password != confirm_password:
            errors.append('Passwords do not match.')

        # Check existing slug or admin email
        if Organization.query.filter_by(slug=org_slug).first():
            errors.append(f"Workspace URL slug '{org_slug}' is already taken. Please pick another one.")
        if User.query.filter_by(email=admin_email).first():
            errors.append(f"An account with email '{admin_email}' already exists. Please sign in or use another email.")

        if errors:
            for err in errors:
                flash(err, 'error')
            return render_template('saas/register_ngo.html', plans=plans, selected_plan_slug=selected_plan_slug)

        # Resolve selected plan
        selected_plan = None
        if plan_id:
            selected_plan = db.session.get(SubscriptionPlan, int(plan_id))
        if not selected_plan:
            selected_plan = SubscriptionPlan.query.filter_by(slug='starter').first()

        # Provision new Organization (Tenant)
        new_org = Organization(
            name=org_name,
            slug=org_slug,
            registration_number=reg_number,
            tagline=tagline or f"Empowering communities with {org_name}",
            description=f"{org_name} is a dedicated charitable organization powered by NGO Cloud SaaS.",
            contact_email=org_email,
            contact_phone=org_phone,
            address=address,
            status='active' if (selected_plan and selected_plan.price_monthly == 0) else 'trial',
            plan_id=selected_plan.id if selected_plan else None,
            trial_ends_at=datetime.now(timezone.utc) + timedelta(days=14)
        )
        db.session.add(new_org)
        db.session.flush()

        # Provision Tenant Subscription record
        sub = TenantSubscription(
            organization_id=new_org.id,
            plan_id=selected_plan.id if selected_plan else 1,
            status='active' if (selected_plan and selected_plan.price_monthly == 0) else 'trial',
            billing_cycle='monthly',
            amount_paid=0.0,
            payment_reference='ONBOARDING-TRIAL',
            start_date=datetime.now(timezone.utc),
            end_date=datetime.now(timezone.utc) + timedelta(days=14)
        )
        db.session.add(sub)

        # Get or create Admin role
        admin_role = Role.query.filter_by(role_name='Admin').first()
        if not admin_role:
            admin_role = Role(role_name='Admin')
            db.session.add(admin_role)
            db.session.flush()

        # Provision initial Admin user
        admin_user = User(
            full_name=admin_name,
            email=admin_email,
            password_hash=generate_password_hash(password),
            role_id=admin_role.id,
            status='active',
            organization_id=new_org.id,
            is_superadmin=False,
            member_id_code=f"{org_slug.upper()[:4]}-ADM-001"
        )
        db.session.add(admin_user)
        db.session.commit()

        # Automatically log in the newly registered NGO admin
        login_user(admin_user, remember=True)
        flash(f"Welcome to your new NGO Cloud workspace: {new_org.name}! Your workspace is now live.", 'success')
        return redirect(url_for('portals.dashboard'))

    return render_template('saas/register_ngo.html', plans=plans, selected_plan_slug=selected_plan_slug)


@saas_bp.route('/directory', endpoint='directory')
def directory():
    """
    Public Multi-Tenant NGO Directory where donors and volunteers
    can discover verified registered organizations.
    """
    search_q = request.args.get('q', '').strip()
    query = Organization.query.filter_by(status='active')
    
    if search_q:
        query = query.filter(
            (Organization.name.ilike(f'%{search_q}%')) |
            (Organization.tagline.ilike(f'%{search_q}%')) |
            (Organization.address.ilike(f'%{search_q}%'))
        )
    
    organizations = query.order_by(Organization.created_at.desc()).all()
    return render_template('saas/directory.html', organizations=organizations, search_q=search_q)


@saas_bp.route('/check-slug')
def check_slug():
    """Real-time AJAX endpoint to verify slug availability during onboarding."""
    slug = request.args.get('slug', '').strip()
    slug = _slugify(slug)
    if not slug:
        return jsonify({'available': False, 'slug': ''})
    exists = Organization.query.filter_by(slug=slug).first() is not None
    return jsonify({'available': not exists, 'slug': slug})
