from flask import render_template, redirect, url_for, flash, request, jsonify, abort
from flask_login import login_required, current_user
from app.extensions import db
from app.core import bp
from app.core.models.contact import Contact
from app.core.models import Category
from app.core.services.audit import AuditService
from app.core.decorators import permission_required
from app.core.forms_contact import ContactForm
from app.core.utils.datatables import apply_datatable_order

@bp.route('/contacts')
@login_required
@permission_required('crm.access')
def list_contacts():
    """
    Renders the main contact management list page.
    """
    return render_template('core/contacts/list.html', title='Contacts')

@bp.route('/contacts/data')
@login_required
@permission_required('crm.access')
def list_contacts_data():
    """
    Server-side processing for the Contact list DataTable.
    Provides searching and sorting across name, company, and email.
    """
    query = Contact.query_active().options(db.joinedload(Contact.category))

    # Search Logic
    search = request.args.get('search[value]')
    if search:
        query = query.filter(
            (Contact.name.ilike(f'%{search}%')) |
            (Contact.company.ilike(f'%{search}%')) |
            (Contact.email.ilike(f'%{search}%'))
        )

    # Ordering Logic
    if request.args.get('order[0][column]') is None:
        query = query.order_by(Contact.created_at.desc())
    else:
        query = apply_datatable_order(
            query,
            request.args,
            {
                '0': Contact.name,
                '1': Contact.company,
                '2': Contact.position,
                '3': Contact.email,
                '4': Contact.phone,
            },
        )

    # Pagination
    start = int(request.args.get('start', 0))
    length = int(request.args.get('length', 10))
    total_filtered = query.count()
    total_records = Contact.query_active().count()

    contacts = query.offset(start).limit(length).all()

    data = []
    for c in contacts:
        data.append({
            'id': c.id,
            'name': c.name,
            'category': c.category.name if c.category else '-',
            'category_id': c.category_id or '',
            'company': c.company,
            'position': c.position,
            'email': c.email,
            'phone': c.phone,
            'address': c.address
        })

    return jsonify({
        'draw': int(request.args.get('draw', 1)),
        'recordsTotal': total_records,
        'recordsFiltered': total_filtered,
        'data': data
    })


@bp.route('/contacts/search')
@login_required
@permission_required('crm.access')
def search_contacts_select2():
    """
    AJAX endpoint for Select2-compatible contact searching.
    Includes company name in the display label for better identification.
    """
    query_text = (request.args.get('q') or '').strip()
    page = max(request.args.get('page', type=int, default=1), 1)
    per_page = 20
    selected_id = (request.args.get('id') or '').strip()

    if selected_id:
        selected_contact = db.session.get(Contact, selected_id)
        if selected_contact and selected_contact.deleted_at is None:
            label = f"{selected_contact.name} ({selected_contact.company or 'No Company'})"
            return jsonify({'results': [{'id': selected_contact.id, 'text': label}]})

    query = Contact.query_active()
    if query_text:
        like = f'%{query_text}%'
        query = query.filter(
            db.or_(
                Contact.name.ilike(like),
                Contact.company.ilike(like),
                Contact.email.ilike(like),
            )
        )

    pagination = query.order_by(Contact.name.asc()).paginate(page=page, per_page=per_page, error_out=False)
    results = [
        {
            'id': contact.id,
            'text': f"{contact.name} ({contact.company or 'No Company'})",
        }
        for contact in pagination.items
    ]

    return jsonify({'results': results, 'pagination': {'more': pagination.has_next}})

@bp.route('/contacts/create', methods=['POST'])
@login_required
@permission_required('crm.access')
def create_contact():
    """
    Creates a new contact record. 
    Restricted to users with CRM access permissions.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    form = ContactForm()
    form.category_id.choices = [(c.id, c.name) for c in Category.query.filter_by(module='crm').all()] + [('', 'None')]

    if form.validate_on_submit():
        contact = Contact(
            name=form.name.data,
            category_id=form.category_id.data if form.category_id.data else None,
            company=form.company.data,
            position=form.position.data,
            email=form.email.data,
            phone=form.phone.data,
            address=form.address.data
        )
        contact.save()
        AuditService.log(contact, 'CREATE', new_data=form.data)
        
        if is_ajax:
            return jsonify({'status': 'success', 'message': 'Contact created successfully'}), 201
            
        flash('Contact created successfully', 'success')
    else:
        if is_ajax:
            errors = {field: [str(e) for e in errs] for field, errs in form.errors.items()}
            return jsonify({'status': 'error', 'message': 'Validation failed', 'errors': errors}), 400
            
        flash('Error creating contact. Please check your input.', 'danger')

    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400

    return redirect(url_for('core.list_contacts'))

@bp.route('/contacts/<id>/edit', methods=['POST'])
@login_required
@permission_required('crm.access')
def edit_contact(id):
    """
    Updates an existing contact's profile information.
    """
    contact = db.session.get(Contact, id)
    if not contact:
        abort(404)

    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    form = ContactForm()
    form.category_id.choices = [(c.id, c.name) for c in Category.query.filter_by(module='crm').all()] + [('', 'None')]

    if form.validate_on_submit():
        old_data = {
            'name': contact.name, 'company': contact.company,
            'email': contact.email, 'phone': contact.phone
        }

        contact.name = form.name.data
        contact.category_id = form.category_id.data if form.category_id.data else None
        contact.company = form.company.data
        contact.position = form.position.data
        contact.email = form.email.data
        contact.phone = form.phone.data
        contact.address = form.address.data

        contact.save()
        AuditService.log(contact, 'UPDATE', old_data=old_data, new_data=form.data)
        
        if is_ajax:
            return jsonify({'status': 'success', 'message': 'Contact updated successfully'}), 200
            
        flash('Contact updated successfully', 'success')
    else:
        if is_ajax:
            errors = {field: [str(e) for e in errs] for field, errs in form.errors.items()}
            return jsonify({'status': 'error', 'message': 'Validation failed', 'errors': errors}), 400
            
        flash('Error updating contact.', 'danger')

    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400

    return redirect(url_for('core.list_contacts'))

@bp.route('/contacts/<id>/delete', methods=['POST'])
@login_required
@permission_required('crm.access')
def delete_contact(id):
    """
    Performs soft deletion of a contact record.
    """
    contact = db.session.get(Contact, id)
    if not contact:
        abort(404)

    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )

    contact.soft_delete(str(current_user.id))
    AuditService.log(contact, 'DELETE')
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Contact deleted successfully'}), 200
        
    flash('Contact deleted successfully', 'success')
    return redirect(url_for('core.list_contacts'))
