{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}Manage Surveys for {{ stage.name }} - PX360{% endblock %}

{% block extra_css %}
<style>
.page-header-gradient {
    background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
    color: white;
    padding: 1.5rem 2rem;
    border-radius: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
}

.form-section {
    background: #fff;
    border: 2px solid #e2e8f0;
    border-radius: 1rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
}
.form-section:hover {
    border-color: #005696;
    box-shadow: 0 4px 12px rgba(0, 86, 150, 0.1);
}

.form-label {
    display: block;
    font-size: 0.875rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.form-control, .form-select {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-size: 0.875rem;
    transition: all 0.2s ease;
}
.form-control:focus, .form-select:focus {
    outline: none;
    border-color: #005696;
    box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
}

.hh-btn-primary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: #005696;
    color: white;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
}
.hh-btn-primary:hover {
    background: #007bbd;
}

.hh-btn-secondary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: white;
    color: #64748b;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
}
.hh-btn-secondary:hover {
    background: #f1f5f9;
    border-color: #005696;
}

.btn-danger {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    background: #ef4444;
    color: white;
    border-radius: 0.5rem;
    font-weight: 500;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
}
.btn-danger:hover {
    background: #dc2626;
}

.table-container {
    overflow-x: auto;
}

.data-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}
.data-table th {
    background: #f8fafc;
    padding: 0.75rem 1rem;
    text-align: left;
    font-size: 0.75rem;
    font-weight: 600;
    color: #475569;
    text-transform: uppercase;
    border-bottom: 2px solid #e2e8f0;
}
.data-table td {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid #e2e8f0;
}
.data-table tr:hover td {
    background: #f8fafc;
}
</style>
{% endblock %}

{% block content %}
<!-- Back Button -->
<div class="mb-6">
    <a href="{% url 'journeys:template_detail' template.pk %}" class="inline-flex items-center gap-2 text-slate hover:text-navy transition">
        <i data-lucide="arrow-left" class="w-4 h-4"></i>
        <span class="text-sm font-medium">{% trans "Back to Template" %}</span>
    </a>
</div>

<!-- Header -->
<div class="page-header-gradient">
    <div class="flex justify-between items-start">
        <div>
            <h1 class="text-2xl font-bold flex items-center gap-3">
                <i data-lucide="file-text" class="w-6 h-6"></i>
                {% trans "Manage Surveys for" %} {{ stage.name }}
            </h1>
            <p class="text-sm mt-1 opacity-90">{% trans "Journey:" %} {{ template.name }}</p>
        </div>
    </div>
</div>

<form method="post" id="surveysForm">
    {% csrf_token %}
    
    <!-- Stage Information -->
    <div class="form-section">
        <h2 class="text-sm font-bold text-navy mb-4">{% trans "Stage Information" %}</h2>
        <div class="grid grid-cols-2 gap-6">
            <div>
                <table class="w-full">
                    <tr>
                        <th class="text-left text-sm font-semibold text-slate py-2" width="40%">{% trans "Stage Name:" %}</th>
                        <td class="text-sm text-slate-700 py-2">{{ stage.name }} ({{ stage.name_ar|default:"-" }})</td>
                    </tr>
                    <tr>
                        <th class="text-left text-sm font-semibold text-slate py-2">{% trans "Order:" %}</th>
                        <td class="text-sm text-slate-700 py-2">{{ stage.order }}</td>
                    </tr>
                </table>
            </div>
            <div>
                <table class="w-full">
                    <tr>
                        <th class="text-left text-sm font-semibold text-slate py-2" width="40%">{% trans "Template Name:" %}</th>
                        <td class="text-sm text-slate-700 py-2">{{ template.name }}</td>
                    </tr>
                    <tr>
                        <th class="text-left text-sm font-semibold text-slate py-2">{% trans "Hospital:" %}</th>
                        <td class="text-sm text-slate-700 py-2">{{ template.hospital.get_localized_name }}</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Surveys -->
    <div class="form-section">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-sm font-bold text-navy">{% trans "Assigned Surveys" %}</h2>
            <button type="button" class="hh-btn hh-btn-primary" id="addSurveyBtn">
                <i data-lucide="plus" class="w-4 h-4"></i> {% trans "Add Survey" %}
            </button>
        </div>
        
        <div id="surveys-container">
            {{ formset.management_form }}
            
            <div class="table-container">
                <table class="data-table" id="surveysTable">
                    <thead>
                        <tr>
                            <th width="60%">{% trans "Survey Template" %}</th>
                            <th width="30%">{% trans "Send After (Hours)" %}</th>
                            <th width="10%">{% trans "Actions" %}</th>
                        </tr>
                    </thead>
                    <tbody id="surveys-body">
                        {% for form in formset %}
                        <tr class="survey-form" id="survey-{{ forloop.counter0 }}">
                            {{ form.id }}
                            <td>
                                {{ form.survey_template }}
                                {% if form.survey_template.errors %}
                                <div class="text-red-500 text-xs mt-1">{{ form.survey_template.errors }}</div>
                                {% endif %}
                            </td>
                            <td>
                                {{ form.send_after_hours }}
                                {% if form.send_after_hours.errors %}
                                <div class="text-red-500 text-xs mt-1">{{ form.send_after_hours.errors }}</div>
                                {% endif %}
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn-danger delete-survey-btn">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            
            {% if not formset %}
            <div class="text-center py-8">
                <i data-lucide="inbox" class="w-12 h-12 text-slate-300 mx-auto mb-3"></i>
                <p class="text-slate mb-4">{% trans "No surveys assigned yet" %}</p>
                <button type="button" class="hh-btn hh-btn-primary" id="addFirstSurveyBtn">
                    <i data-lucide="plus" class="w-4 h-4"></i> {% trans "Add First Survey" %}
                </button>
            </div>
            {% endif %}
            
            <div class="mt-4 flex items-center gap-2 text-sm text-slate">
                <i data-lucide="info" class="w-4 h-4"></i>
                <span>{% trans "Surveys will be sent to patients automatically after the specified number of hours from when the stage is triggered." %}</span>
            </div>
        </div>
    </div>
    
    <!-- Form Actions -->
    <div class="form-section">
        <div class="flex justify-end gap-3">
            <a href="{% url 'journeys:template_detail' template.pk %}" class="hh-btn hh-btn-secondary">
                <i data-lucide="x-circle" class="w-4 h-4"></i> {% trans "Cancel" %}
            </a>
            <button type="submit" class="hh-btn hh-btn-primary">
                <i data-lucide="check-circle" class="w-4 h-4"></i> {% trans "Save Changes" %}
            </button>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const surveysBody = document.getElementById('surveys-body');
    const addSurveyBtn = document.getElementById('addSurveyBtn');
    const addFirstSurveyBtn = document.getElementById('addFirstSurveyBtn');
    let totalFormsInput = document.getElementById('id_surveys-TOTAL_FORMS');
    
    // Guard against missing essential elements
    if (!surveysBody) {
        console.error('Surveys body not found');
        return;
    }
    
    // Create management form input if it doesn't exist (create form scenario)
    if (!totalFormsInput) {
        totalFormsInput = document.createElement('input');
        totalFormsInput.type = 'hidden';
        totalFormsInput.id = 'id_surveys-TOTAL_FORMS';
        totalFormsInput.name = 'surveys-TOTAL_FORMS';
        totalFormsInput.value = '0';
        surveysBody.appendChild(totalFormsInput);
    }
    
    // Delete survey button handler
    surveysBody.addEventListener('click', function(e) {
        if (e.target.closest('.delete-survey-btn')) {
            const row = e.target.closest('tr');
            const idInput = row.querySelector('[name$="-id"]');
            
            if (idInput && idInput.value) {
                // Existing record - mark for deletion
                const deleteInput = document.createElement('input');
                deleteInput.type = 'hidden';
                deleteInput.name = idInput.name.replace('id', 'DELETE');
                deleteInput.value = 'on';
                row.appendChild(deleteInput);
                row.style.display = 'none';
            } else {
                // New record - just remove
                row.remove();
            }
        }
    });
    
    // Add new survey helper function
    function addSurvey() {
        const formCount = totalFormsInput ? parseInt(totalFormsInput.value) : 0;
        const newRow = document.createElement('tr');
        newRow.className = 'survey-form';
        newRow.id = 'survey-' + formCount;
        
        // Get available survey templates from existing forms
        let surveyOptions = '';
        const firstSurveySelect = surveysBody.querySelector('select[name$="-survey_template"]');
        if (firstSurveySelect) {
            surveyOptions = firstSurveySelect.innerHTML;
        }
        
        newRow.innerHTML = `
            <input type="hidden" name="surveys-${formCount}-id" id="id_surveys-${formCount}-id">
            <td>
                <select name="surveys-${formCount}-survey_template" 
                        id="id_surveys-${formCount}-survey_template" 
                        class="form-select">
                    ${surveyOptions}
                </select>
            </td>
            <td>
                <input type="number" name="surveys-${formCount}-send_after_hours" 
                       id="id_surveys-${formCount}-send_after_hours" 
                       class="form-control" value="24" min="0" step="1">
            </td>
            <td class="text-center">
                <button type="button" class="btn-danger delete-survey-btn">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </td>
        `;
        
        if (surveysBody) {
            surveysBody.appendChild(newRow);
            if (totalFormsInput) {
                totalFormsInput.value = formCount + 1;
            }
            // Initialize lucide icons for new elements
            if (window.lucide) {
                window.lucide.createIcons();
            }
        } else {
            // Create table body if it doesn't exist
            const newBody = document.createElement('tbody');
            newBody.id = 'surveys-body';
            newBody.appendChild(newRow);
            const table = document.getElementById('surveysTable');
            if (table) {
                table.appendChild(newBody);
                if (totalFormsInput) {
                    totalFormsInput.value = formCount + 1;
                }
                // Initialize lucide icons for new elements
                if (window.lucide) {
                    window.lucide.createIcons();
                }
            }
        }
    }
    
    // Add new survey button handler
    if (addSurveyBtn) {
        addSurveyBtn.addEventListener('click', addSurvey);
    }
    
    if (addFirstSurveyBtn) {
        addFirstSurveyBtn.addEventListener('click', addSurvey);
    }
});
</script>
{% endblock %}
