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

{% block title %}{% if template %}Edit {{ template.name }}{% else %}Create Journey Template{% endif %} - 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;
}

.form-check {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.form-check-input {
    width: 1rem;
    height: 1rem;
}
</style>
{% endblock %}

{% block content %}
<!-- Back Button -->
<div class="mb-6">
    <a href="{% url 'journeys:template_list' %}" 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 Templates" %}</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">
                {% if template %}
                <i data-lucide="pencil" class="w-6 h-6"></i>{% trans "Edit" %} {{ template.name }}
                {% else %}
                <i data-lucide="plus-circle" class="w-6 h-6"></i>{% trans "Create Journey Template" %}
                {% endif %}
            </h1>
            <p class="text-sm mt-1 opacity-90">{% trans "Define stages and surveys for patient journeys" %}</p>
        </div>
    </div>
</div>

<form method="post" id="templateForm">
    {% csrf_token %}
    
    <!-- Template Details -->
    <div class="form-section">
        <h2 class="text-sm font-bold text-navy mb-4">{% trans "Template Details" %}</h2>
        <div class="grid grid-cols-3 gap-6">
            <div>
                <label for="{{ form.name.id_for_label }}" class="form-label">{% trans "Name (English)" %} *</label>
                {{ form.name }}
                {% if form.name.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.name.errors }}</div>
                {% endif %}
            </div>
            <div>
                <label for="{{ form.name_ar.id_for_label }}" class="form-label">{% trans "Name (Arabic)" %}</label>
                {{ form.name_ar }}
                {% if form.name_ar.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.name_ar.errors }}</div>
                {% endif %}
            </div>
            <div>
                <label for="{{ form.journey_type.id_for_label }}" class="form-label">{% trans "Journey Type" %} *</label>
                {{ form.journey_type }}
                {% if form.journey_type.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.journey_type.errors }}</div>
                {% endif %}
            </div>
        </div>
        
        <div class="grid grid-cols-2 gap-6 mt-6">
            <div>
                <label for="{{ form.hospital.id_for_label }}" class="form-label">{% trans "Hospital" %} *</label>
                {{ form.hospital }}
                {% if form.hospital.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.hospital.errors }}</div>
                {% endif %}
            </div>
            <div>
                <label for="{{ form.is_active.id_for_label }}" class="form-label">{% trans "Status" %}</label>
                <div class="form-check mt-2">
                    {{ form.is_active }}
                    <label class="text-sm text-slate" for="{{ form.is_active.id_for_label }}">{% trans "Active" %}</label>
                </div>
                {% if form.is_active.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.is_active.errors }}</div>
                {% endif %}
            </div>
        </div>
        
        <div class="grid grid-cols-2 gap-6 mt-6">
            <div>
                <label for="{{ form.send_post_discharge_survey.id_for_label }}" class="form-label">{% trans "Post-Discharge Survey" %}</label>
                <div class="form-check mt-2">
                    {{ form.send_post_discharge_survey }}
                    <label class="text-sm text-slate" for="{{ form.send_post_discharge_survey.id_for_label }}">{% trans "Send comprehensive survey after discharge" %}</label>
                </div>
                {% if form.send_post_discharge_survey.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.send_post_discharge_survey.errors }}</div>
                {% endif %}
            </div>
            <div>
                <label for="{{ form.post_discharge_survey_delay_hours.id_for_label }}" class="form-label">{% trans "Survey Delay (Hours)" %}</label>
                {{ form.post_discharge_survey_delay_hours }}
                {% if form.post_discharge_survey_delay_hours.errors %}
                <div class="text-red-500 text-xs mt-1">{{ form.post_discharge_survey_delay_hours.errors }}</div>
                {% endif %}
                <div class="text-xs text-slate mt-1">{% trans "Hours after discharge to send the survey" %}</div>
            </div>
        </div>
        
        <div class="mt-6">
            <label for="{{ form.description.id_for_label }}" class="form-label">{% trans "Description" %}</label>
            {{ form.description }}
            {% if form.description.errors %}
            <div class="text-red-500 text-xs mt-1">{{ form.description.errors }}</div>
            {% endif %}
        </div>
    </div>
    
    <!-- Stages -->
    <div class="form-section">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-sm font-bold text-navy">{% trans "Journey Stages" %}</h2>
            <button type="button" class="hh-btn hh-btn-primary" id="addStageBtn">
                <i data-lucide="plus" class="w-4 h-4"></i> {% trans "Add Stage" %}
            </button>
        </div>
        <div id="stages-container">
            {{ formset.management_form }}
            
            <div class="table-container">
                <table class="data-table" id="stagesTable">
                    <thead>
                        <tr>
                            <th width="8%">{% trans "Order" %}</th>
                            <th width="25%">{% trans "Name (EN)" %}</th>
                            <th width="15%">{% trans "Code" %}</th>
                            <th width="20%">{% trans "Trigger Event" %}</th>
                            <th width="10%">{% trans "Survey" %}</th>
                            <th width="7%">{% trans "Opt" %}</th>
                            <th width="7%">{% trans "Act" %}</th>
                            <th width="8%">{% trans "Actions" %}</th>
                        </tr>
                    </thead>
                    <tbody id="stages-body">
                        {% for form in formset %}
                        <tr class="stage-form" id="stage-{{ forloop.counter0 }}">
                            {{ form.id }}
                            <td>
                                {{ form.order }}
                            </td>
                            <td>
                                {{ form.name }}
                                <small class="text-slate-500 block">{{ form.name_ar }}</small>
                            </td>
                            <td>
                                {{ form.code }}
                            </td>
                            <td>
                                {{ form.trigger_event_code }}
                            </td>
                            <td>
                                {{ form.survey_template }}
                            </td>
                            <td class="text-center">
                                <div class="form-check justify-center">
                                    {{ form.is_optional }}
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check justify-center">
                                    {{ form.is_active }}
                                </div>
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn-danger delete-stage-btn">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            
            <div class="mt-4 space-y-2">
                <div class="flex items-center gap-2 text-sm text-slate">
                    <i data-lucide="info" class="w-4 h-4"></i>
                    <span><strong>{% trans "Stages" %}</strong>: {% trans "Define stages for patient journeys. Each stage has a trigger event code that completes the stage. Survey templates assigned here will have their questions merged into the post-discharge survey." %}</span>
                </div>
                <div class="flex items-center gap-2 text-sm text-slate">
                    <i data-lucide="info" class="w-4 h-4"></i>
                    <span>{% trans "Stages will be executed in order. After creating the template, you can assign surveys to each stage." %}</span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Form Actions -->
    <div class="form-section">
        <div class="flex justify-end gap-3">
            <a href="{% url 'journeys:template_list' %}" 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>
                {% if template %}{% trans "Update Template" %}{% else %}{% trans "Create Template" %}{% endif %}
            </button>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const stagesBody = document.getElementById('stages-body');
    const addStageBtn = document.getElementById('addStageBtn');
    let totalFormsInput = document.getElementById('id_stagesset-TOTAL_FORMS');
    
    // Guard against missing essential elements
    if (!stagesBody || !addStageBtn) {
        console.error('Required elements 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_stagesset-TOTAL_FORMS';
        totalFormsInput.name = 'stagesset-TOTAL_FORMS';
        totalFormsInput.value = '0';
        stagesBody.appendChild(totalFormsInput);
    }
    
    // Delete stage button handler
    stagesBody.addEventListener('click', function(e) {
        if (e.target.closest('.delete-stage-btn')) {
            const row = e.target.closest('tr');
            const deleteInput = document.createElement('input');
            deleteInput.type = 'hidden';
            deleteInput.name = row.querySelector('[name$="-id"]').name.replace('id', 'DELETE');
            deleteInput.value = 'on';
            row.appendChild(deleteInput);
            row.style.display = 'none';
            updateStageOrders();
        }
    });
    
    // Add new stage
    addStageBtn.addEventListener('click', function() {
        const formCount = parseInt(totalFormsInput.value);
        const newRow = document.createElement('tr');
        newRow.className = 'stage-form';
        newRow.id = 'stage-' + formCount;
        
        // Get survey template options from first row
        let surveyOptions = '<option value="">-- No Survey --</option>';
        const firstSurveySelect = document.querySelector('select[name$="-survey_template"]');
        if (firstSurveySelect) {
            surveyOptions = firstSurveySelect.innerHTML;
        }
        
        newRow.innerHTML = `
            <input type="hidden" name="stagesset-${formCount}-id" id="id_stagesset-${formCount}-id">
            <td>
                <input type="number" name="stagesset-${formCount}-order" 
                       id="id_stagesset-${formCount}-order" 
                       class="form-control form-control-sm" value="${formCount + 1}" min="0">
            </td>
            <td>
                <input type="text" name="stagesset-${formCount}-name" 
                       id="id_stagesset-${formCount}-name" 
                       class="form-control form-control-sm" placeholder="e.g., Admission">
                <input type="text" name="stagesset-${formCount}-name_ar" 
                       id="id_stagesset-${formCount}-name_ar" 
                       class="form-control form-control-sm mt-1" placeholder="الاسم بالعربية" style="font-size: 0.8rem;">
            </td>
            <td>
                <input type="text" name="stagesset-${formCount}-code" 
                       id="id_stagesset-${formCount}-code" 
                       class="form-control form-control-sm" placeholder="e.g., ADMISSION">
            </td>
            <td>
                <input type="text" name="stagesset-${formCount}-trigger_event_code" 
                       id="id_stagesset-${formCount}-trigger_event_code" 
                       class="form-control form-control-sm" placeholder="e.g., OPD_VISIT_COMPLETED">
            </td>
            <td>
                <select name="stagesset-${formCount}-survey_template" 
                        id="id_stagesset-${formCount}-survey_template" 
                        class="form-select form-select-sm">
                    ${surveyOptions}
                </select>
            </td>
            <td class="text-center">
                <div class="form-check justify-center">
                    <input type="checkbox" name="stagesset-${formCount}-is_optional" 
                           id="id_stagesset-${formCount}-is_optional" 
                           class="form-check-input">
                </div>
            </td>
            <td class="text-center">
                <div class="form-check justify-center">
                    <input type="checkbox" name="stagesset-${formCount}-is_active" 
                           id="id_stagesset-${formCount}-is_active" 
                           class="form-check-input" checked>
                </div>
            </td>
            <td class="text-center">
                <button type="button" class="btn-danger delete-stage-btn">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </td>
        `;
        
        stagesBody.appendChild(newRow);
        totalFormsInput.value = formCount + 1;
        
        // Initialize lucide icons for new elements
        if (window.lucide) {
            window.lucide.createIcons();
        }
    });
    
    // Update stage orders when rows are deleted
    function updateStageOrders() {
        const visibleRows = Array.from(stagesBody.querySelectorAll('tr:not([style*="display: none"])'));
        visibleRows.forEach((row, index) => {
            const orderInput = row.querySelector('[name$="-order"]');
            if (orderInput) {
                orderInput.value = index;
            }
        });
    }
    
    // Initial order update
    updateStageOrders();
});
</script>
{% endblock %}
