from flask import render_template, redirect, url_for, flash, request, abort, jsonify
from flask_login import login_required, current_user
from app.extensions import db
from app.core import bp
from app.core.decorators import permission_required
from app.core.models import Office, Employee
from app.core.forms_office import OfficeForm
from app.core.services.audit import AuditService

@bp.route('/settings/offices')
@login_required
@permission_required('hris.access')
def list_offices():
    """
    Renders the office management list page.
    Enforces Admin role or 'hris.manage' permissions for access.
    """
    if not current_user.is_admin() and not (current_user.has_permission('hris.access') or current_user.has_permission('hris.manage')):
        abort(403)

    offices = Office.query.filter(Office.deleted_at.is_(None)).all()
    return render_template('core/offices/list.html', offices=offices, title='Manage Offices')

@bp.route('/settings/offices/create', methods=['POST'])
@login_required
@permission_required('hris.manage')
def create_office():
    """
    Creates a new office location record. 
    Requires specific coordinates and radius for geofencing support.
    """
    if not current_user.is_admin() and not current_user.has_permission('hris.manage'):
        abort(403)

    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    form = OfficeForm()
    
    if form.validate_on_submit():
        office = Office(
            name=form.name.data,
            address=form.address.data,
            latitude=form.latitude.data,
            longitude=form.longitude.data,
            radius_meters=form.radius_meters.data
        )
        office.save()
        AuditService.log(office, 'CREATE', new_data=form.data)
        
        if is_ajax:
            return jsonify({
                'status': 'success', 
                'message': 'Office created successfully',
                'office': {
                    'id': office.id,
                    'name': office.name,
                    'address': office.address,
                    'latitude': office.latitude,
                    'longitude': office.longitude,
                    'radius_meters': office.radius_meters
                }
            }), 201
            
        flash('Office 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
            
        for field, errors in form.errors.items():
            for error in errors:
                flash(f"Error in {field}: {error}", 'danger')

    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400
        
    return redirect(url_for('core.list_offices'))

@bp.route('/settings/offices/<id>/edit', methods=['POST'])
@login_required
@permission_required('hris.manage')
def edit_office(id):
    """
    Updates an existing office's details, including its geofencing parameters.
    """
    if not current_user.is_admin() and not current_user.has_permission('hris.manage'):
        abort(403)

    office = db.session.get(Office, id)
    if not office:
        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 = OfficeForm()
    
    if form.validate_on_submit():
        old_data = {
            'name': office.name, 'address': office.address,
            'lat': office.latitude, 'lng': office.longitude, 'rad': office.radius_meters
        }

        office.name = form.name.data
        office.address = form.address.data
        office.latitude = form.latitude.data
        office.longitude = form.longitude.data
        office.radius_meters = form.radius_meters.data

        office.save()
        AuditService.log(office, 'UPDATE', old_data=old_data, new_data=form.data)
        
        if is_ajax:
            return jsonify({
                'status': 'success', 
                'message': 'Office updated successfully',
                'office': {
                    'id': office.id,
                    'name': office.name,
                    'address': office.address,
                    'latitude': office.latitude,
                    'longitude': office.longitude,
                    'radius_meters': office.radius_meters
                }
            }), 200
            
        flash('Office 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
            
        for field, errors in form.errors.items():
            for error in errors:
                flash(f"Error in {field}: {error}", 'danger')

    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400
        
    return redirect(url_for('core.list_offices'))

@bp.route('/settings/offices/<id>/delete', methods=['POST'])
@login_required
@permission_required('hris.manage')
def delete_office(id):
    """
    Performs soft deletion of an office record. 
    Prevents deletion if there are active employees assigned to the location.
    """
    if not current_user.is_admin() and not current_user.has_permission('hris.manage'):
        abort(403)

    office = db.session.get(Office, id)
    if not office:
        abort(404)

    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )

    # Usage validation to ensure data integrity
    usage = Employee.query.filter_by(office_id=id).count()
    if usage > 0:
        msg = f'Cannot delete office. It has {usage} employees assigned.'
        if is_ajax:
            return jsonify({'status': 'error', 'message': msg}), 400
        flash(msg, 'danger')
        return redirect(url_for('core.list_offices'))

    office.soft_delete(str(current_user.id))
    AuditService.log(office, 'DELETE')
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Office deleted successfully'}), 200
        
    flash('Office deleted successfully', 'success')
    return redirect(url_for('core.list_offices'))
