{% extends 'base/layout.html' %}
{% load render_table from django_tables2 %}
{% load i18n %}
{% load static %}

{% block title %}{{ device.name }} - {% trans "Maintenance" %}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h2">
                <a href="{{ device.get_absolute_url }}" class="text-decoration-none">{{ device.name }}</a>
                <span class="text-muted">/</span>
                {% trans "Maintenance" %}
            </h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'dcim:device_list' %}">{% trans "Devices" %}</a></li>
                    <li class="breadcrumb-item"><a href="{{ device.get_absolute_url }}">{{ device.name }}</a></li>
                    <li class="breadcrumb-item active">{% trans "Maintenance" %}</li>
                </ol>
            </nav>
        </div>
        <div class="btn-group">
            {% if perms.netbox_maintenance_device.add_maintenanceplan %}
                <a href="{% url 'plugins:netbox_maintenance_device:maintenanceplan_add' %}?device={{ device.pk }}" class="btn btn-primary">
                    <i class="mdi mdi-plus-thick" aria-hidden="true"></i> {% trans "Add Plan" %}
                </a>
            {% endif %}
            {% if perms.netbox_maintenance_device.add_maintenanceexecution %}
                <a href="{% url 'plugins:netbox_maintenance_device:maintenanceexecution_add' %}?device={{ device.pk }}" class="btn btn-outline-primary">
                    <i class="mdi mdi-wrench" aria-hidden="true"></i> {% trans "Add Execution" %}
                </a>
            {% endif %}
        </div>
    </div>

<link rel="stylesheet" href="{% static 'netbox_maintenance_device/css/maintenance.css' %}">>

<div class="row">
    <div class="col col-md-12">
        <div class="card">
            <h5 class="card-header">
                <i class="mdi mdi-calendar-clock"></i> {% trans "Maintenance Plans" %}
                <div class="card-actions">
                    {% if perms.netbox_maintenance_device.add_maintenanceplan %}
                        <a href="{% url 'plugins:netbox_maintenance_device:maintenanceplan_add' %}?device={{ device.pk }}" class="btn btn-sm btn-primary">
                            <i class="mdi mdi-plus-thick" aria-hidden="true"></i> {% trans "Add Plan" %}
                        </a>
                    {% endif %}
                </div>
            </h5>
            <div class="card-body">
                {% if maintenance_plans %}
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>{% trans "Name" %}</th>
                                <th>{% trans "Type" %}</th>
                                <th>{% trans "Frequency" %}</th>
                                <th>{% trans "Next Due" %}</th>
                                <th>{% trans "Status" %}</th>
                                <th>{% trans "Actions" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for plan in maintenance_plans %}
                            <tr {% if plan.is_overdue %}class="table-danger"{% elif plan.days_until_due and plan.days_until_due <= 7 %}class="table-warning"{% endif %}>
                                <td><a href="{{ plan.get_absolute_url }}">{{ plan.name }}</a></td>
                                <td>{{ plan.get_maintenance_type_display }}</td>
                                <td>{{ plan.frequency_days }} {% trans "days" %}</td>
                                <td>
                                    {% with next_date=plan.get_next_maintenance_date %}
                                        {% if next_date %}
                                            {{ next_date|date:"d/m/Y" }}
                                            {% if plan.is_overdue %}
                                                <span class="badge badge-danger">
                                                    <i class="mdi mdi-alert-circle"></i> {% trans "Overdue" %}
                                                </span>
                                            {% elif plan.days_until_due and plan.days_until_due <= 7 %}
                                                <span class="badge badge-warning">
                                                    <i class="mdi mdi-clock-alert"></i> {% trans "Due Soon" %}
                                                </span>
                                            {% endif %}
                                        {% else %}
                                            -
                                        {% endif %}
                                    {% endwith %}
                                </td>
                                <td>
                                    {% if plan.is_active %}
                                        <span class="badge badge-success">{% trans "Active" %}</span>
                                    {% else %}
                                        <span class="badge badge-secondary">{% trans "Inactive" %}</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if plan.is_overdue or plan.days_until_due and plan.days_until_due <= 7 %}
                                        <button class="btn btn-sm btn-success quick-complete" 
                                                data-plan-id="{{ plan.pk }}" 
                                                data-device-id="{{ device.pk }}"
                                                title="{% trans 'Schedule Immediate Maintenance' %}">
                                            <i class="mdi mdi-check-circle"></i> {% trans "Schedule" %}
                                        </button>
                                    {% endif %}
                                    <a href="{{ plan.get_absolute_url }}" class="btn btn-sm btn-outline-primary" title="{% trans 'View Details' %}">
                                        <i class="mdi mdi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                {% else %}
                    <div class="alert alert-info">
                        <i class="mdi mdi-information"></i>
                        {% trans "No maintenance plans configured for this device." %}
                        {% if perms.netbox_maintenance_device.add_maintenanceplan %}
                            <a href="{% url 'plugins:netbox_maintenance_device:maintenanceplan_add' %}?device={{ device.pk }}" class="btn btn-sm btn-primary ml-2">
                                <i class="mdi mdi-plus-thick" aria-hidden="true"></i> {% trans "Add Plan" %}
                            </a>
                        {% endif %}
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<div class="row mt-3">
    <div class="col col-md-12">
        <div class="card">
            <h5 class="card-header">
                <i class="mdi mdi-history"></i> {% trans "Recent Maintenance History" %}
                <div class="card-actions">
                    {% if perms.netbox_maintenance_device.add_maintenanceexecution %}
                        <a href="{% url 'plugins:netbox_maintenance_device:maintenanceexecution_add' %}" class="btn btn-sm btn-primary">
                            <i class="mdi mdi-plus-thick" aria-hidden="true"></i> {% trans "Add Execution" %}
                        </a>
                    {% endif %}
                </div>
            </h5>
            <div class="card-body">
                {% if recent_executions %}
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>{% trans "Plan" %}</th>
                                <th>{% trans "Scheduled" %}</th>
                                <th>{% trans "Completed" %}</th>
                                <th>{% trans "Status" %}</th>
                                <th>{% trans "Technician" %}</th>
                                <th>{% trans "Actions" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for execution in recent_executions %}
                            <tr>
                                <td><a href="{{ execution.get_absolute_url }}">{{ execution.maintenance_plan.name }}</a></td>
                                <td>{{ execution.scheduled_date|date:"d/m/Y H:i" }}</td>
                                <td>
                                    {% if execution.completed_date %}
                                        {{ execution.completed_date|date:"d/m/Y H:i" }}
                                    {% else %}
                                        -
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="badge {% if execution.status == 'completed' %}badge-success{% elif execution.status == 'in_progress' %}badge-warning{% elif execution.status == 'cancelled' %}badge-danger{% else %}badge-info{% endif %}">
                                        {{ execution.get_status_display }}
                                    </span>
                                </td>
                                <td>{{ execution.technician|default:"-" }}</td>
                                <td>
                                    {% if execution.status != 'completed' and execution.status != 'cancelled' %}
                                        <button class="btn btn-sm btn-success complete-execution" 
                                                data-execution-id="{{ execution.pk }}"
                                                title="{% trans 'Mark as Completed' %}">
                                            <i class="mdi mdi-check"></i> {% trans "Complete" %}
                                        </button>
                                    {% endif %}
                                    <a href="{{ execution.get_absolute_url }}" class="btn btn-sm btn-outline-primary" title="{% trans 'View Details' %}">
                                        <i class="mdi mdi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                    <div class="text-center mt-3">
                        <a href="{% url 'plugins:netbox_maintenance_device:maintenanceexecution_list' %}?maintenance_plan__device={{ device.pk }}" class="btn btn-outline-primary">
                            <i class="mdi mdi-history"></i> {% trans "View all maintenance history" %} →
                        </a>
                    </div>
                {% else %}
                    <div class="alert alert-info">
                        <i class="mdi mdi-information"></i>
                        {% trans "No maintenance executions recorded for this device." %}
                        {% if perms.netbox_maintenance_device.add_maintenanceexecution %}
                            <a href="{% url 'plugins:netbox_maintenance_device:maintenanceexecution_add' %}?device={{ device.pk }}" class="btn btn-sm btn-primary ml-2">
                                <i class="mdi mdi-wrench" aria-hidden="true"></i> {% trans "Add Execution" %}
                            </a>
                        {% endif %}
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Quick Completion Modal -->
<div class="modal fade" id="quickCompleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{% trans "Complete Maintenance" %}</h5>
            </div>
            <div class="modal-body">
                <form id="quickCompleteForm">
                    {% csrf_token %}
                    <input type="hidden" id="executionId" name="execution_id">
                    <input type="hidden" id="planId" name="plan_id">
                    <input type="hidden" id="deviceId" name="device_id">
                    <div class="form-group">
                        <label for="technician">{% trans "Technician" %}</label>
                        <input type="text" class="form-control" id="technician" name="technician">
                    </div>
                    <div class="form-group">
                        <label for="notes">{% trans "Notes" %}</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans "Cancel" %}</button>
                <button type="button" class="btn btn-success" id="confirmComplete">{% trans "Complete Maintenance" %}</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get CSRF token from cookies
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    const csrftoken = getCookie('csrftoken');
    
    // Modal helper functions
    function showModal(modalId) {
        const modalEl = document.getElementById(modalId);
        if (!modalEl) return;
        
        // Try Bootstrap 5 first
        if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
            const modal = new bootstrap.Modal(modalEl);
            modal.show();
        }
        // Then Bootstrap 4
        else if (typeof $ !== 'undefined' && $.fn.modal) {
            $(modalEl).modal('show');
        }
        // Fallback to manual display
        else {
            modalEl.style.display = 'block';
            modalEl.classList.add('show');
            document.body.classList.add('modal-open');
            
            const backdrop = document.createElement('div');
            backdrop.className = 'modal-backdrop fade show';
            backdrop.id = modalId + '-backdrop';
            document.body.appendChild(backdrop);
        }
    }
    
    function hideModal(modalId) {
        const modalEl = document.getElementById(modalId);
        if (!modalEl) return;
        
        // Try Bootstrap 5 first
        if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
            const modal = bootstrap.Modal.getInstance(modalEl);
            if (modal) modal.hide();
        }
        // Then Bootstrap 4
        else if (typeof $ !== 'undefined' && $.fn.modal) {
            $(modalEl).modal('hide');
        }
        // Fallback to manual hide
        else {
            modalEl.style.display = 'none';
            modalEl.classList.remove('show');
            document.body.classList.remove('modal-open');
            
            const backdrop = document.getElementById(modalId + '-backdrop');
            if (backdrop) backdrop.remove();
        }
    }
    
    // Handle quick completion for maintenance plans
    document.addEventListener('click', function(e) {
        if (e.target.closest('.quick-complete')) {
            e.preventDefault();
            const btn = e.target.closest('.quick-complete');
            const planId = btn.dataset.planId;
            const deviceId = btn.dataset.deviceId;
            
            document.getElementById('planId').value = planId;
            document.getElementById('deviceId').value = deviceId;
            document.getElementById('executionId').value = '';
            showModal('quickCompleteModal');
        }
    });
    
    // Handle completion for existing executions
    document.addEventListener('click', function(e) {
        if (e.target.closest('.complete-execution')) {
            e.preventDefault();
            const btn = e.target.closest('.complete-execution');
            const executionId = btn.dataset.executionId;
            
            document.getElementById('executionId').value = executionId;
            document.getElementById('planId').value = '';
            document.getElementById('deviceId').value = '';
            showModal('quickCompleteModal');
        }
    });
    
    // Handle modal close buttons
    document.addEventListener('click', function(e) {
        if (e.target.matches('[data-dismiss="modal"]') || e.target.closest('[data-dismiss="modal"]')) {
            const modal = e.target.closest('.modal');
            if (modal) {
                hideModal(modal.id);
            }
        }
    });
    
    // Handle form submission
    const confirmCompleteBtn = document.getElementById('confirmComplete');
    if (confirmCompleteBtn) {
        confirmCompleteBtn.addEventListener('click', function() {
            this.disabled = true;
            this.innerHTML = '<i class="mdi mdi-loading mdi-spin"></i> {% trans "Processing..." %}';
            
            const form = document.getElementById('quickCompleteForm');
            const formData = new FormData(form);
            
            fetch('{% url "plugins:netbox_maintenance_device:quick_complete" %}', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrftoken
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('{% trans "Error completing maintenance" %}: ' + data.error);
                    this.disabled = false;
                    this.innerHTML = '{% trans "Complete Maintenance" %}';
                }
            })
            .catch(error => {
                let errorMsg = '{% trans "Error completing maintenance" %}';
                if (error.responseJSON && error.responseJSON.error) {
                    errorMsg += ': ' + error.responseJSON.error;
                }
                alert(errorMsg);
                this.disabled = false;
                this.innerHTML = '{% trans "Complete Maintenance" %}';
            });
        });
    }
    
    // Reset form when modal is hidden
    const quickCompleteModal = document.getElementById('quickCompleteModal');
    if (quickCompleteModal) {
        quickCompleteModal.addEventListener('hidden.bs.modal', function() {
            document.getElementById('quickCompleteForm').reset();
            const btn = document.getElementById('confirmComplete');
            btn.disabled = false;
            btn.innerHTML = '{% trans "Complete Maintenance" %}';
        });
    }
});
</script>
</div>
{% endblock %}