"""
Billing routes - Subscription and payment management
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from app import db
from app.models import User
from datetime import datetime, timedelta

billing_bp = Blueprint('billing', __name__)


@billing_bp.route('/')
@login_required
def index():
    """Billing dashboard"""
    # Get user subscription info
    user = User.query.get(current_user.id)

    # Calculate days until expiration
    days_until_expiry = None
    if user.subscription_expires_at:
        days_until_expiry = (user.subscription_expires_at - datetime.utcnow()).days

    return render_template('billing/index.html',
                         user=user,
                         days_until_expiry=days_until_expiry)


@billing_bp.route('/subscribe/<plan>')
@login_required
def subscribe(plan):
    """Initiate subscription for a plan"""
    valid_plans = ['pro', 'scale']

    if plan not in valid_plans:
        flash('Invalid plan selected.', 'error')
        return redirect(url_for('billing.index'))

    # TODO: Implement Stripe checkout session creation
    # For now, just upgrade immediately (for testing)
    flash(f'Subscription to {plan.capitalize()} plan initiated.', 'info')
    return redirect(url_for('billing.index'))


@billing_bp.route('/webhook/stripe', methods=['POST'])
def stripe_webhook():
    """Handle Stripe webhook events"""
    # TODO: Implement Stripe webhook signature verification
    # TODO: Handle subscription.created, subscription.updated, invoice.payment_succeeded, etc.

    return jsonify({'status': 'success'}), 200


@billing_bp.route('/cancel', methods=['POST'])
@login_required
def cancel_subscription():
    """Cancel user subscription"""
    # TODO: Implement subscription cancellation through Stripe
    flash('Subscription cancellation requested.', 'info')
    return redirect(url_for('billing.index'))


@billing_bp.route('/update-payment-method', methods=['GET', 'POST'])
@login_required
def update_payment_method():
    """Update payment method"""
    # TODO: Implement payment method update through Stripe
    if request.method == 'POST':
        flash('Payment method updated.', 'success')
        return redirect(url_for('billing.index'))

    return render_template('billing/update_payment.html')


@billing_bp.route('/history')
@login_required
def payment_history():
    """View payment history"""
    # TODO: Implement payment history retrieval
    return render_template('billing/history.html')


@billing_bp.route('/invoices/<invoice_id>')
@login_required
def download_invoice(invoice_id):
    """Download invoice PDF"""
    # TODO: Implement invoice download from Stripe
    pass
