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.modules.hris import bp
from app.modules.hris.models import Shift, Holiday, Employee, Attendance
from app.modules.hris.forms_admin import ShiftForm, HolidayForm, AttendanceForm
from app.core.models import Status
from app.core.decorators import permission_required
from app.core.services.audit import AuditService
from datetime import datetime, time

# --- Shifts Management ---

@bp.route('/admin/shifts')
@login_required
@permission_required('hris.access')
def list_shifts():
    """
    Renders the management list page for working shifts.
    """
    shifts = Shift.query.filter(Shift.deleted_at.is_(None)).all()
    return render_template('hris/admin/shifts_list.html', shifts=shifts, title='Manage Shifts')

@bp.route('/admin/shifts/create', methods=['POST'])
@login_required
@permission_required('hris.manage')
def create_shift():
    """
    Creates a new shift configuration with specific start and end times.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    form = ShiftForm()
    if form.validate_on_submit():
        shift = Shift(
            name=form.name.data,
            start_time=form.start_time.data,
            end_time=form.end_time.data,
            is_overtime_allowed=form.is_overtime_allowed.data
        )
        shift.save()
        AuditService.log(shift, 'CREATE', new_data=form.data)
        _notify_hr_manager_audit(
            'Shift Created',
            f'New shift created: {shift.name} ({shift.start_time} - {shift.end_time}).',
            link=url_for('hris.list_shifts')
        )
        
        if is_ajax:
            return jsonify({'status': 'success', 'message': 'Shift created successfully'}), 201
        flash('Shift 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 shift', 'danger')
        
    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400
    return redirect(url_for('hris.list_shifts'))

@bp.route('/admin/shifts/<id>/edit', methods=['POST'])
@login_required
@permission_required('hris.manage')
def edit_shift(id):
    """
    Updates an existing shift's operational parameters.
    """
    shift = db.session.get(Shift, id)
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    
    if not shift:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Shift not found'}), 404
        abort(404)

    form = ShiftForm()
    if form.validate_on_submit():
        shift.name = form.name.data
        shift.start_time = form.start_time.data
        shift.end_time = form.end_time.data
        shift.is_overtime_allowed = form.is_overtime_allowed.data
        shift.save()
        AuditService.log(shift, 'UPDATE', new_data=form.data)
        
        if is_ajax:
            return jsonify({'status': 'success', 'message': 'Shift updated successfully'}), 200
        flash('Shift 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 shift', 'danger')

    if is_ajax:
        return jsonify({'status': 'error', 'message': 'Invalid request'}), 400
    return redirect(url_for('hris.list_shifts'))

@bp.route('/admin/shifts/<id>/delete', methods=['POST'])
@login_required
@permission_required('hris.manage')
def delete_shift(id):
    """
    Performs soft deletion of a shift record. 
    Prevents deletion if the shift is currently assigned to any employee schedules.
    """
    shift = db.session.get(Shift, id)
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    
    if not shift:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Shift not found'}), 404
        abort(404)

    # Usage validation to prevent orphan schedule references
    from app.modules.hris.models.schedule import EmployeeSchedule
    usage = EmployeeSchedule.query.filter_by(shift_id=id).count()
    if usage > 0:
        msg = f'Cannot delete shift. It is assigned to {usage} active schedules.'
        if is_ajax: return jsonify({'status': 'error', 'message': msg}), 400
        flash(msg, 'danger')
        return redirect(url_for('hris.list_shifts'))

    shift.soft_delete(str(current_user.id))
    AuditService.log(shift, 'DELETE')
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Shift deleted successfully'}), 200
        
    flash('Shift deleted successfully', 'success')
    return redirect(url_for('hris.list_shifts'))

# --- Holidays Management ---

@bp.route('/admin/holidays')
@login_required
@permission_required('hris.access')
def list_holidays():
    """
    Renders the management list for organizational holidays.
    Sorted by date descending to show recent/upcoming events first.
    """
    holidays = Holiday.query.filter(Holiday.deleted_at.is_(None)).order_by(Holiday.date.desc()).all()
    return render_template('hris/admin/holidays_list.html', holidays=holidays, title='Manage Holidays')

@bp.route('/admin/holidays/create', methods=['POST'])
@login_required
@permission_required('hris.manage')
def create_holiday():
    """
    Registers a new holiday record in the system.
    """
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    form = HolidayForm()
    if form.validate_on_submit():
        holiday = Holiday(
            name=form.name.data,
            date=form.date.data,
            is_recurring=form.is_recurring.data
        )
        holiday.save()
        AuditService.log(holiday, 'CREATE', new_data=form.data)
        
        if is_ajax:
            return jsonify({'status': 'success', 'message': 'Holiday created successfully'}), 201
        flash('Holiday 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 holiday', 'danger')
        
    if is_ajax: return jsonify({'status': 'error', 'message': 'Invalid request'}), 400
    return redirect(url_for('hris.list_holidays'))

@bp.route('/admin/holidays/<id>/delete', methods=['POST'])
@login_required
@permission_required('hris.manage')
def delete_holiday(id):
    """
    Performs soft deletion of a holiday record.
    """
    holiday = db.session.get(Holiday, id)
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    
    if not holiday:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Holiday not found'}), 404
        abort(404)

    holiday.soft_delete(str(current_user.id))
    AuditService.log(holiday, 'DELETE')
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Holiday deleted successfully'}), 200
        
    flash('Holiday deleted successfully', 'success')
    return redirect(url_for('hris.list_holidays'))


# --- Manual Attendance Management ---

@bp.route('/admin/attendance/create', methods=['POST'])
@login_required
@permission_required('hris.manage')
def create_attendance():
    """
    Allows HR Managers to manually record attendance for an employee. 
    Used for retroactive corrections or exceptions.
    """
    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
    employee_id = data.get('employee_id')
    status_id = data.get('status_id')
    date_val = data.get('date')
    check_in = data.get('check_in')
    check_out = data.get('check_out')
    notes = data.get('notes')

    if not all([employee_id, status_id, date_val]):
        if is_ajax: return jsonify({'status': 'error', 'message': 'Missing required fields'}), 400
        flash('Missing required fields', 'danger')
        return redirect(url_for('hris.admin_attendance'))

    # Time conversion logic
    try:
        in_time = datetime.strptime(f"{date_val} {check_in}", "%Y-%m-%d %H:%M") if check_in else None
        out_time = datetime.strptime(f"{date_val} {check_out}", "%Y-%m-%d %H:%M") if check_out else None
    except ValueError:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Invalid time format'}), 400
        flash('Invalid time format', 'danger')
        return redirect(url_for('hris.admin_attendance', date=date_val))

    attn = Attendance(
        employee_id=employee_id,
        date=datetime.strptime(date_val, '%Y-%m-%d').date(),
        status_id=status_id,
        check_in=in_time,
        check_out=out_time
    )

    # Ensure unique daily records per employee
    existing = Attendance.query.filter_by(employee_id=employee_id, date=attn.date).first()
    if existing:
        msg = 'Attendance record already exists for this employee on this date.'
        if is_ajax: return jsonify({'status': 'error', 'message': msg}), 400
        flash(msg, 'warning')
        return redirect(url_for('hris.admin_attendance', date=date_val))

    attn.save()
    AuditService.log(attn, 'CREATE', new_data={'reason': notes, 'manual_entry': True})
    
    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Attendance record created successfully.'}), 201
        
    flash('Attendance record created successfully.', 'success')
    return redirect(url_for('hris.admin_attendance', date=date_val))

@bp.route('/admin/attendance/<id>/edit', methods=['POST'])
@login_required
@permission_required('hris.manage')
def edit_attendance(id):
    """
    Updates an existing attendance record. 
    Maintains audit logs for manual overrides.
    """
    attn = db.session.get(Attendance, id)
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' or (
        request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html
    )
    
    if not attn:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Attendance record not found'}), 404
        abort(404)

    data = request.get_json() if request.is_json else request.form
    date_val = data.get('date')
    check_in = data.get('check_in')
    check_out = data.get('check_out')
    status_id = data.get('status_id')
    notes = data.get('notes')

    old_data = {'in': attn.check_in, 'out': attn.check_out, 'status': attn.status_id}

    # Apply updates
    attn.status_id = status_id
    try:
        if check_in:
            attn.check_in = datetime.strptime(f"{date_val} {check_in}", "%Y-%m-%d %H:%M")
        if check_out:
            attn.check_out = datetime.strptime(f"{date_val} {check_out}", "%Y-%m-%d %H:%M")
    except ValueError:
        if is_ajax: return jsonify({'status': 'error', 'message': 'Invalid time format'}), 400
        flash('Invalid time format', 'danger')
        return redirect(url_for('hris.admin_attendance', date=date_val))

    attn.save()
    AuditService.log(attn, 'UPDATE', old_data=old_data, new_data={'reason': notes, 'manual_override': True})

    if is_ajax:
        return jsonify({'status': 'success', 'message': 'Attendance updated successfully.'}), 200
        
    flash('Attendance updated successfully.', 'success')
    return redirect(url_for('hris.admin_attendance', date=date_val))


def _notify_hr_manager_audit(title: str, message: str, link: str | None = None) -> None:
    """
    Internal helper to send administrative notifications to the HR Management team.
    """
    from app.core.services.notification import NotificationService
    NotificationService.send_to_role_names(
        ['HR Manager'],
        title,
        message,
        link=link,
        exclude_user_ids=[current_user.id],
    )
