from flask import render_template, request, flash, redirect, url_for, abort, jsonify
from flask_login import login_required, current_user
from app.extensions import db
from app.modules.collaboration import bp
from app.modules.collaboration.models import Note, Message
from app.core.models.user import User
from app.core.decorators import permission_required
from app.core.services.alerts import AlertService

@bp.route('/workspace')
@login_required
@permission_required('collab.access')
async def workspace():
    """
    Renders the collaboration personal workspace.
    Displays active sticky notes and system alerts for the current user.
    """
    # Capture user_id before entering async context to avoid Flask-Login proxy issues
    user_id = current_user.id
    
    # Filter only active (non-soft-deleted) notes owned by the user
    notes = Note.query_active().filter_by(owner_id=user_id).order_by(Note.created_at.desc()).all()
    
    # Run async alert fetching
    try:
        alerts = await AlertService.get_actionable_alerts(user_id)
    except Exception:
        # Fallback if there are async issues
        alerts = []
    
    return render_template('collaboration/workspace.html', 
                           notes=notes, 
                           alerts=alerts, 
                           title='My Workspace')

@bp.route('/notes/create', methods=['POST'])
@login_required
@permission_required('collab.access')
def create_note():
    """
    Creates a new personal sticky note.
    Supports both standard form submission and AJAX requests.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    data = request.get_json() if request.is_json else request.form
    
    title = data.get('title', '')
    content = data.get('content')
    color = data.get('color', 'warning')
    
    if content:
        note = Note(title=title, content=content, color=color, owner_id=current_user.id)
        db.session.add(note)
        db.session.commit()
        
        if is_ajax: 
            return jsonify({'status': 'success', 'message': 'Note created successfully'}), 201
        flash('Note created', 'success')
    else:
        if is_ajax: 
            return jsonify({'status': 'error', 'message': 'Content is required'}), 400
        flash('Note content cannot be empty.', 'danger')
        
    return redirect(url_for('collaboration.workspace'))

@bp.route('/notes/<id>/edit', methods=['POST'])
@login_required
@permission_required('collab.access')
def edit_note(id):
    """
    Updates an existing sticky note.
    Verifies ownership before applying changes.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    # Fetch via query_active to ensure soft-deleted notes are inaccessible
    note = Note.query_active().filter_by(id=id).first()
    
    if not note or note.owner_id != current_user.id:
        if is_ajax: 
            return jsonify({'status': 'error', 'message': 'Note not found or unauthorized'}), 404
        abort(404)

    data = request.get_json() if request.is_json else request.form
    note.title = data.get('title', note.title)
    note.content = data.get('content', note.content)
    note.color = data.get('color', note.color)
    
    db.session.commit()
    
    if is_ajax: 
        return jsonify({'status': 'success', 'message': 'Note updated successfully'}), 200
    flash('Note updated', 'success')
    return redirect(url_for('collaboration.workspace'))

@bp.route('/notes/<id>/delete', methods=['POST'])
@login_required
@permission_required('collab.access')
def delete_note(id):
    """
    Performs a soft deletion of a personal note.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    note = Note.query_active().filter_by(id=id).first()
    
    if not note or note.owner_id != current_user.id:
        if is_ajax: 
            return jsonify({'status': 'error', 'message': 'Note not found or unauthorized'}), 404
        abort(404)

    # Standard soft delete implementation from BaseModel
    note.soft_delete(user_id=str(current_user.id))
    
    if is_ajax: 
        return jsonify({'status': 'success', 'message': 'Note deleted'}), 200
    flash('Note deleted', 'success')
    return redirect(url_for('collaboration.workspace'))

@bp.route('/inbox')
@login_required
@permission_required('collab.access')
def inbox():
    """
    Renders the internal Direct Mail inbox for the user.
    """
    # Fetch non-deleted messages received by the user
    messages = Message.query_active().filter_by(recipient_id=current_user.id).order_by(Message.created_at.desc()).all()
    unread_count = Message.query_active().filter_by(recipient_id=current_user.id, is_read=False).count()
    
    return render_template('collaboration/inbox.html',
                           messages=messages, 
                           unread_count=unread_count, 
                           title='Internal Mail')

@bp.route('/messages/send', methods=['POST'])
@login_required
@permission_required('collab.access')
def send_message():
    """
    Sends an internal message to another system user.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    data = request.get_json() if request.is_json else request.form
    
    recipient_id = data.get('recipient_id')
    subject = data.get('subject')
    body = data.get('body')

    if not recipient_id or not subject or not body:
        if is_ajax: 
            return jsonify({'status': 'error', 'message': 'Recipient, subject, and body are required'}), 400
        flash('All fields are required to send a message.', 'danger')
        return redirect(url_for('collaboration.inbox'))

    msg = Message(
        sender_id=current_user.id,
        recipient_id=recipient_id,
        subject=subject,
        body=body
    )
    db.session.add(msg)
    db.session.commit()

    if is_ajax: 
        return jsonify({'status': 'success', 'message': 'Message sent successfully'}), 201
    flash('Message sent', 'success')
    return redirect(url_for('collaboration.inbox'))

@bp.route('/messages/<id>/read', methods=['POST'])
@login_required
@permission_required('collab.access')
def mark_read(id):
    """
    Marks an internal message as read via AJAX or standard post.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    msg = db.session.get(Message, id)
    
    if not msg or msg.recipient_id != current_user.id:
        if is_ajax: 
            return jsonify({'status': 'error', 'message': 'Message not found or unauthorized'}), 404
        abort(404)

    msg.is_read = True
    db.session.commit()
    
    if is_ajax: 
        return jsonify({'status': 'success', 'message': 'Message marked as read'}), 200
    return redirect(url_for('collaboration.inbox'))

@bp.route('/messages/<id>/detail')
@login_required
@permission_required('collab.access')
def message_detail(id):
    """
    Returns message detail as JSON for AJAX loading in inbox.
    Also marks the message as read if the recipient is viewing.
    """
    msg = db.session.get(Message, id)
    
    if not msg or msg.recipient_id != current_user.id:
        return jsonify({'status': 'error', 'message': 'Message not found or unauthorized'}), 404
    
    # Auto-mark as read when viewing detail
    if not msg.is_read:
        msg.is_read = True
        db.session.commit()
    
    sender = db.session.get(User, msg.sender_id)
    return jsonify({
        'status': 'success',
        'message': {
            'id': msg.id,
            'sender_name': sender.display_name if sender else 'Unknown',
            'sender_email': sender.email if sender else '',
            'subject': msg.subject,
            'body': msg.body,
            'is_read': msg.is_read,
            'created_at': msg.created_at.strftime('%d %b %Y, %H:%M') if msg.created_at else ''
        }
    })

@bp.route('/messages/<id>/delete', methods=['POST'])
@login_required
@permission_required('collab.access')
def delete_message(id):
    """
    Soft deletes a message from the recipient's inbox.
    Only the recipient can delete their received messages.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    
    msg = Message.query_active().filter_by(id=id, recipient_id=current_user.id).first()
    
    if not msg:
        if is_ajax:
            return jsonify({'status': 'error', 'message': 'Message not found or unauthorized'}), 404
        abort(404)
    
    # Soft delete using BaseModel method
    msg.soft_delete(user_id=str(current_user.id))
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Message deleted successfully'}), 200
    flash('Message deleted', 'success')
    return redirect(url_for('collaboration.inbox'))

@bp.route('/messages/unread-count')
@login_required
@permission_required('collab.access')
def unread_count():
    """
    Returns the unread message count for the current user.
    Used for sidebar/navbar badge updates.
    """
    count = Message.query_active().filter_by(recipient_id=current_user.id, is_read=False).count()
    return jsonify({'status': 'success', 'count': count})
