"""SaaS Tenant Workspace & Public Portal Blueprint.

Handles:
1. Tenant Admin Billing & Plan Quotas (/admin/billing)
2. Tenant NGO Custom Branding & Profile (/admin/organization/branding)
3. Public Tenant NGO Microsite / Portal (/org/<slug>)
"""

from datetime import datetime, timezone, timedelta
from flask import Blueprint, render_template, request, redirect, url_for, flash, abort, jsonify
from flask_login import login_required, current_user

from app.extensions import db
from app.models.organization import Organization, TenantSubscription
from app.models.subscription_plan import SubscriptionPlan
from app.models.campaign import Campaign
from app.models.donation import Donation
from app.models.programme_pillar import ProgrammePillar
from app.services.permissions import roles_required
from app.services.tenant_service import get_current_tenant, get_tenant_metrics


saas_tenant_bp = Blueprint('saas_tenant', __name__)


# ------------------------------------------------------------------------------
# 1. Tenant Admin: Billing & Plan Upgrades
# ------------------------------------------------------------------------------
@saas_tenant_bp.route('/admin/billing', methods=['GET', 'POST'], endpoint='billing')
@roles_required('Admin')
def billing():
    """
    NGO Admin Billing Dashboard.
    Visualizes current SaaS plan, quota utilization (staff, donations, campaigns),
    and allows seamless tier upgrades.
    """
    tenant = get_current_tenant()
    if not tenant:
        flash('No active organization found.', 'error')
        return redirect(url_for('portals.dashboard'))

    metrics = get_tenant_metrics(tenant)
    available_plans = SubscriptionPlan.query.filter_by(is_active=True).order_by(SubscriptionPlan.price_monthly.asc()).all()

    if request.method == 'POST':
        action = request.form.get('action')
        if action == 'upgrade_plan':
            plan_id = request.form.get('plan_id', type=int)
            new_plan = db.session.get(SubscriptionPlan, plan_id)
            if new_plan:
                tenant.plan_id = new_plan.id
                tenant.status = 'active'
                
                # Record subscription
                sub = TenantSubscription(
                    organization_id=tenant.id,
                    plan_id=new_plan.id,
                    status='active',
                    billing_cycle=request.form.get('billing_cycle', 'monthly'),
                    amount_paid=new_plan.price_monthly,
                    payment_reference=f"SUB-UPGRADE-{datetime.now().strftime('%Y%m%d%H%M')}",
                    start_date=datetime.now(timezone.utc),
                    end_date=datetime.now(timezone.utc) + timedelta(days=30 if request.form.get('billing_cycle') != 'yearly' else 365)
                )
                db.session.add(sub)
                db.session.commit()
                flash(f"Workspace upgraded successfully to {new_plan.name}!", 'success')
                return redirect(url_for('saas_tenant.billing'))

    subscriptions = tenant.subscriptions.order_by(TenantSubscription.id.desc()).limit(10).all()

    return render_template(
        'admin/billing.html',
        tenant=tenant,
        metrics=metrics,
        available_plans=available_plans,
        subscriptions=subscriptions
    )


# ------------------------------------------------------------------------------
# 2. Tenant Admin: Organization Branding & Settings
# ------------------------------------------------------------------------------
@saas_tenant_bp.route('/admin/organization/branding', methods=['GET', 'POST'], endpoint='branding')
@roles_required('Admin')
def branding():
    """
    NGO Admin Branding and Profile Customization.
    Allows configuring custom colors, logo, tagline, and official registration details.
    """
    tenant = get_current_tenant()
    if not tenant:
        flash('No active organization found.', 'error')
        return redirect(url_for('portals.dashboard'))

    if request.method == 'POST':
        tenant.name = request.form.get('name', tenant.name).strip()
        tenant.tagline = request.form.get('tagline', '').strip()
        tenant.description = request.form.get('description', '').strip()
        tenant.logo_url = request.form.get('logo_url', '').strip()
        tenant.primary_color = request.form.get('primary_color', '#102a43').strip()
        tenant.secondary_color = request.form.get('secondary_color', '#0284c7').strip()
        tenant.contact_email = request.form.get('contact_email', tenant.contact_email).strip().lower()
        tenant.contact_phone = request.form.get('contact_phone', '').strip()
        tenant.address = request.form.get('address', '').strip()
        tenant.website_url = request.form.get('website_url', '').strip()
        tenant.registration_number = request.form.get('registration_number', '').strip()

        db.session.commit()
        flash('Organization branding and profile updated successfully!', 'success')
        return redirect(url_for('saas_tenant.branding'))

    return render_template('admin/branding.html', tenant=tenant)


# ------------------------------------------------------------------------------
# 3. Public Multi-Tenant Portal (/org/<slug>)
# ------------------------------------------------------------------------------
@saas_tenant_bp.route('/org/<slug>', endpoint='tenant_portal')
def tenant_portal(slug):
    """
    Dedicated Public Portal for a specific NGO.
    Renders that NGO's unique branding, tagline, active fundraising campaigns,
    programme pillars, and direct intake links.
    """
    org = Organization.query.filter_by(slug=slug).first_or_404()
    campaigns = Campaign.query.order_by(Campaign.id.desc()).limit(6).all()
    pillars = ProgrammePillar.query.order_by(ProgrammePillar.id.asc()).limit(6).all()

    return render_template(
        'public/tenant_portal.html',
        org=org,
        campaigns=campaigns,
        pillars=pillars
    )


@saas_tenant_bp.route('/org/<slug>/donate', endpoint='tenant_donate')
def tenant_donate(slug):
    """
    Pre-scoped donation page for a specific NGO tenant.
    """
    org = Organization.query.filter_by(slug=slug).first_or_404()
    campaigns = Campaign.query.order_by(Campaign.id.desc()).all()
    return render_template('public/donate.html', designated_org=org, campaigns=campaigns)
