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

{% block title %}{% if is_create %}{% trans "Create Template" %}{% else %}{% trans "Edit 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;
}

.task-template-item {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 0.75rem;
    padding: 1rem;
    transition: all 0.2s ease;
}
.task-template-item:hover {
    border-color: #005696;
}
</style>
{% endblock %}

{% block content %}
<!-- Back Button -->
<div class="mb-6">
    <a href="{% url 'projects: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">
    <h1 class="text-2xl font-bold flex items-center gap-3">
        <i data-lucide="layout-template" class="w-6 h-6"></i>
        {% if is_create %}{% trans "Create Project Template" %}{% else %}{% trans "Edit Project Template" %}{% endif %}
    </h1>
    <p class="text-sm mt-1 opacity-90">
        {% if is_create %}
            {% trans "Create a reusable template for quality improvement projects" %}
        {% else %}
            {% trans "Update template details and task templates" %}
        {% endif %}
    </p>
</div>

<div class="grid grid-cols-3 gap-6">
    <!-- Main Form -->
    <div class="col-span-2">
        <div class="form-section">
            <h2 class="text-sm font-bold text-navy mb-4">{% trans "Template Information" %}</h2>
            
            <form method="post" novalidate>
                {% csrf_token %}
                
                <div class="grid grid-cols-2 gap-6">
                    <!-- Name -->
                    <div>
                        <label for="{{ form.name.id_for_label }}" class="form-label">
                            {% trans "Template Name" %} <span class="text-red-500">*</span>
                        </label>
                        {{ form.name }}
                        {% if form.name.errors %}
                        <p class="text-red-500 text-xs mt-1">{{ form.name.errors.0 }}</p>
                        {% endif %}
                    </div>
                    
                    <!-- Is Active -->
                    <div>
                        <label for="{{ form.is_active.id_for_label }}" class="form-label">
                            {% trans "Status" %}
                        </label>
                        {{ form.is_active }}
                        {% if form.is_active.errors %}
                        <p class="text-red-500 text-xs mt-1">{{ form.is_active.errors.0 }}</p>
                        {% endif %}
                    </div>
                </div>

                <!-- Description -->
                <div class="mt-6">
                    <label for="{{ form.description.id_for_label }}" class="form-label">
                        {% trans "Description" %}
                    </label>
                    {{ form.description }}
                    {% if form.description.errors %}
                    <p class="text-red-500 text-xs mt-1">{{ form.description.errors.0 }}</p>
                    {% endif %}
                </div>

                <!-- Task Templates Formset -->
                <div class="mt-8">
                    <h3 class="text-sm font-bold text-navy mb-4 flex items-center gap-2">
                        <i data-lucide="check-square" class="w-4 h-4"></i>
                        {% trans "Task Templates" %}
                    </h3>
                    
                    {{ formset.management_form }}
                    
                    <div id="task-templates-container" class="space-y-4">
                        {% for task_form in formset %}
                        <div class="task-template-item">
                            <div class="grid grid-cols-12 gap-4 items-start">
                                <div class="col-span-5">
                                    <label class="block text-[10px] font-bold text-slate uppercase tracking-wider mb-1">
                                        {% trans "Task Title" %}
                                    </label>
                                    {{ task_form.title }}
                                    {% if task_form.title.errors %}
                                    <p class="text-red-500 text-[10px] mt-0.5">{{ task_form.title.errors.0 }}</p>
                                    {% endif %}
                                </div>
                                <div class="col-span-5">
                                    <label class="block text-[10px] font-bold text-slate uppercase tracking-wider mb-1">
                                        {% trans "Description" %}
                                    </label>
                                    {{ task_form.description }}
                                </div>
                                <div class="col-span-2 flex items-center gap-2 pt-5">
                                    {{ task_form.DELETE }}
                                    <button type="button" class="remove-task-btn p-2 text-red-600 hover:bg-red-50 rounded-lg transition" title="{% trans 'Remove' %}">
                                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <button type="button" id="add-task-btn" class="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate rounded-xl text-xs font-bold hover:bg-slate-200 transition">
                        <i data-lucide="plus" class="w-3 h-3"></i> {% trans "Add Task Template" %}
                    </button>
                </div>

                <!-- Submit Buttons -->
                <div class="flex items-center gap-3 mt-8 pt-6 border-t">
                    <button type="submit" class="hh-btn hh-btn-primary">
                        <i data-lucide="save" class="w-4 h-4"></i>
                        {% if is_create %}{% trans "Create Template" %}{% else %}{% trans "Save Changes" %}{% endif %}
                    </button>
                    <a href="{% url 'projects:template_list' %}" class="hh-btn hh-btn-secondary">
                        <i data-lucide="x" class="w-4 h-4"></i>
                        {% trans "Cancel" %}
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Sidebar -->
    <div class="col-span-1">
        <div class="form-section">
            <h2 class="text-sm font-bold text-navy mb-4">{% trans "Help" %}</h2>
            <div class="space-y-4">
                <div>
                    <h3 class="text-xs font-bold text-navy mb-1">{% trans "What are templates?" %}</h3>
                    <p class="text-xs text-slate">{% trans "Templates let you define standard project structures that can be reused across your organization." %}</p>
                </div>
                <div>
                    <h3 class="text-xs font-bold text-navy mb-1">{% trans "Task Templates" %}</h3>
                    <p class="text-xs text-slate">{% trans "Add common tasks that should be created automatically when using this template." %}</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Handle task template removal
document.querySelectorAll('.remove-task-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const item = this.closest('.task-template-item');
        const deleteCheckbox = item.querySelector('input[name$="-DELETE"]');
        if (deleteCheckbox) {
            deleteCheckbox.checked = true;
            item.style.display = 'none';
        }
    });
});

// Add new task template (simplified - in production you'd clone an empty form)
document.getElementById('add-task-btn')?.addEventListener('click', function() {
    const container = document.getElementById('task-templates-container');
    let totalForms = document.querySelector('#id_tasktemplate_set-TOTAL_FORMS');
    
    // Guard against missing container
    if (!container) {
        console.error('Task templates container not found');
        return;
    }
    
    // Create management form input if it doesn't exist (create form scenario)
    if (!totalForms) {
        totalForms = document.createElement('input');
        totalForms.type = 'hidden';
        totalForms.id = 'id_tasktemplate_set-TOTAL_FORMS';
        totalForms.name = 'tasktemplate_set-TOTAL_FORMS';
        totalForms.value = '0';
        container.appendChild(totalForms);
    }
    
    const formCount = parseInt(totalForms.value) || 0;
    
    const newForm = document.createElement('div');
    newForm.className = 'task-template-item';
    newForm.innerHTML = `
        <div class="grid grid-cols-12 gap-4 items-start">
            <div class="col-span-5">
                <label class="block text-[10px] font-bold text-slate uppercase tracking-wider mb-1">{% trans "Task Title" %}</label>
                <input type="text" name="tasktemplate_set-${formCount}-title" class="form-control">
            </div>
            <div class="col-span-5">
                <label class="block text-[10px] font-bold text-slate uppercase tracking-wider mb-1">{% trans "Description" %}</label>
                <input type="text" name="tasktemplate_set-${formCount}-description" class="form-control">
            </div>
            <div class="col-span-2 flex items-center gap-2 pt-5">
                <input type="checkbox" name="tasktemplate_set-${formCount}-DELETE" style="display:none">
                <button type="button" class="remove-task-btn p-2 text-red-600 hover:bg-red-50 rounded-lg transition" title="Remove">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </div>
        </div>
    `;
    
    container.appendChild(newForm);
    totalForms.value = formCount + 1;
    
    // Initialize lucide icons for new elements
    if (window.lucide) {
        window.lucide.createIcons();
    }
    
    // Add remove handler
    newForm.querySelector('.remove-task-btn').addEventListener('click', function() {
        newForm.remove();
    });
});
</script>
{% endblock %}
