{% extends 'layouts/base.html' %}
{% load i18n %}
{% load standards_filters %}
{% load action_icons %}

{% block title %}{% trans "Department Standards" %} - {{ department.name }}{% endblock %}

{% block content %}
<div class="container-fluid px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">{{ department.name }}</h1>
            <p class="text-muted mb-0">{% trans "Standards Compliance" %}</p>
        </div>
        <div class="d-flex gap-2">
            {% if is_px_admin %}
            <a href="{% url 'standards:standard_create' department_id=department.id %}" class="btn btn-primary">
                {% action_icon "create" %} {% trans "Add Standard" %}
            </a>
            {% endif %}
            <a href="{% url 'standards:dashboard' %}" class="btn btn-outline-secondary">
                {% action_icon "back" %} {% trans "Back to Dashboard" %}
            </a>
        </div>
    </div>

    <!-- Search -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-12">
                    <input type="text" class="form-control" id="searchInput"
                           placeholder="{% trans 'Search standards...' %}">
                </div>
            </div>
        </div>
    </div>

    <!-- Standards Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">{% trans "Standards List" %}</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="standardsTable">
                    <thead>
                        <tr>
                            <th>{% trans "Code" %}</th>
                            <th>{% trans "Title" %}</th>
                            <th>{% trans "Status" %}</th>
                            <th>{% trans "Evidence" %}</th>
                            <th>{% trans "Actions" %}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in standards_data %}
                        <tr data-standard-id="{{ item.standard.id }}"
                            data-compliance-id="{% if item.compliance %}{{ item.compliance.id }}{% endif %}">
                            <td><strong>{{ item.standard.code }}</strong></td>
                            <td>
                                <a href="{% url 'standards:standard_detail' pk=item.standard.id %}">
                                    {{ item.standard.title }}
                                </a>
                            </td>
                            <td>
                                {% if item.compliance %}
                                <span class="badge {% if item.compliance.status == 'met' %}bg-success{% elif item.compliance.status == 'partially_met' %}bg-warning{% elif item.compliance.status == 'not_met' %}bg-danger{% else %}bg-secondary{% endif %}">
                                    {{ item.compliance.get_status_display }}
                                </span>
                                {% else %}
                                <span class="badge bg-secondary">{% trans "Not Assessed" %}</span>
                                {% endif %}
                            </td>
                            <td>
                                <span class="badge bg-info">
                                    {% action_icon "attachment" %}
                                    {{ item.attachment_count }}
                                </span>
                            </td>
                            <td>
                                {% if item.compliance %}
                                <button class="btn btn-sm btn-primary"
                                        onclick="openAssessModal('{{ item.compliance.id }}')">
                                    {% action_icon "edit" %} {% trans "Assess" %}
                                </button>
                                {% else %}
                                <button class="btn btn-sm btn-success"
                                        onclick="createAndAssess('{{ item.standard.id }}')">
                                    {% action_icon "create" %} {% trans "Assess" %}
                                </button>
                                {% endif %}
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="5" class="text-center text-muted">
                                {% trans "No standards found" %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Compliance Assessment Modal -->
<div class="modal fade" id="assessmentModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{% trans "Compliance Assessment" %}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="assessmentForm">
                <div class="modal-body">
                    <input type="hidden" id="complianceId" name="compliance_id">

                    <div class="mb-3">
                        <label for="status" class="form-label">
                            {% trans "Compliance Status" %} <span class="text-danger">*</span>
                        </label>
                        <select class="form-select" id="status" name="status" required>
                            <option value="not_assessed">{% trans "Not Assessed" %}</option>
                            <option value="met">{% trans "Met" %}</option>
                            <option value="partially_met">{% trans "Partially Met" %}</option>
                            <option value="not_met">{% trans "Not Met" %}</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="last_assessed_date" class="form-label">
                            {% trans "Assessment Date" %}
                        </label>
                        <input type="date" class="form-control" id="last_assessed_date" name="last_assessed_date">
                        <small class="form-text text-muted">
                            {% trans "Auto-filled with today's date" %}
                        </small>
                    </div>

                    <div class="mb-3">
                        <label for="assessor" class="form-label">{% trans "Assessor" %}</label>
                        <input type="text" class="form-control" id="assessor" name="assessor" readonly>
                        <input type="hidden" id="assessor_id" name="assessor_id" value="{{ user.id }}">
                        <small class="form-text text-muted">
                            {% trans "Current logged-in user" %}
                        </small>
                    </div>

                    <div class="mb-3">
                        <label for="notes" class="form-label">{% trans "Notes" %}</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                                  placeholder="{% trans 'Add any notes about the assessment...' %}"></textarea>
                    </div>

                    <div class="mb-3">
                        <label for="evidence_summary" class="form-label">{% trans "Evidence Summary" %}</label>
                        <textarea class="form-control" id="evidence_summary" name="evidence_summary" rows="3"
                                  placeholder="{% trans 'Summarize the evidence supporting this assessment...' %}"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        {% trans "Cancel" %}
                    </button>
                    <button type="submit" class="btn btn-primary">
                        {% action_icon "save" %} {% trans "Save Assessment" %}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// User data from template
const userData = {
    id: '{{ user.id }}',
    username: "{{ user.username }}",
    fullName: "{% if user.get_full_name %}{{ user.get_full_name }}{% else %}{{ user.username }}{% endif %}"
};

let modalInstance = null;

document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap modal
    const modalElement = document.getElementById('assessmentModal');
    if (modalElement) {
        modalInstance = new bootstrap.Modal(modalElement);
    }

    // Set today's date
    const today = new Date().toISOString().split('T')[0];
    const dateInput = document.getElementById('last_assessed_date');
    if (dateInput) {
        dateInput.value = today;
    }

    // Set assessor field
    const assessorInput = document.getElementById('assessor');
    if (assessorInput) {
        assessorInput.value = userData.fullName;
    }

    // Filter functionality
    const searchInput = document.getElementById('searchInput');
    const table = document.getElementById('standardsTable');

    function filterTable() {
        const searchText = searchInput.value.toLowerCase();
        const rows = table.querySelectorAll('tbody tr');

        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            const matchesSearch = text.includes(searchText);

            if (matchesSearch) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    searchInput.addEventListener('input', filterTable);

    // Form submission
    const form = document.getElementById('assessmentForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            submitAssessment();
        });
    }
});

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;
}

function createAndAssess(standardId) {
    // Create compliance record first
    const data = {
        standard_id: standardId,
        department_id: '{{ department.id }}'
    };

    console.log('Creating compliance:', data);

    fetch(`/standards/api/compliance/create/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        console.log('Response status:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);
        if (data.success) {
            // Open modal with new compliance ID
            openAssessModal(data.compliance_id);
        } else {
            alert('Error creating compliance record: ' + (data.error || ''));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error creating compliance record: ' + error);
    });
}

function openAssessModal(complianceId) {
    document.getElementById('complianceId').value = complianceId;
    modalInstance.show();
}

function submitAssessment() {
    const form = document.getElementById('assessmentForm');
    const formData = new FormData(form);

    const compliance_id = document.getElementById('complianceId').value;
    const status = document.getElementById('status').value;
    const notes = document.getElementById('notes').value;
    const evidence_summary = document.getElementById('evidence_summary').value;
    const last_assessed_date = document.getElementById('last_assessed_date').value;
    const assessor_id = document.getElementById('assessor_id').value;

    if (!compliance_id || !status) {
        alert('Missing required fields');
        return;
    }

    const data = {
        compliance_id: compliance_id,
        status: status,
        notes: notes || '',
        evidence_summary: evidence_summary || '',
        last_assessed_date: last_assessed_date || '',
        assessor_id: assessor_id || ''
    };

    console.log('Submitting assessment:', data);

    fetch(`/standards/api/compliance/update/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        console.log('Response status:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);
        if (data.success) {
            modalInstance.hide();
            // Reload page to show updated status
            location.reload();
        } else {
            alert('Error updating compliance: ' + (data.error || ''));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating compliance: ' + error);
    });
}
</script>
{% endblock %}
