{% extends 'base.html' %}
{% load static i18n crispy_forms_tags %}

{% block title %}Form Templates - ATS{% endblock %}

{% block customCSS %}
<style>
    /* ================================================= */
    /* UI Variables (Matching Job List) */
    /* ================================================= */
    :root {
        --kaauh-teal: #00636e;
        --kaauh-teal-dark: #004a53;
        --kaauh-border: #eaeff3;
        --kaauh-primary-text: #343a40;
        --kaauh-gray-light: #f8f9fa;
    }

    /* --- Typography and Color Overrides --- */
    .text-primary { color: var(--kaauh-teal) !important; }

    /* --- Button Base Styles (Matching Job List) --- */
    .btn-main-action {
        background-color: var(--kaauh-teal);
        border-color: var(--kaauh-teal);
        color: white;
        font-weight: 600;
        padding: 0.375rem 0.75rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }
    .btn-main-action:hover {
        background-color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal-dark);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        color: white;
    }

    /* Secondary Button Style (for Edit/Preview) */
    .btn-outline-secondary {
        color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal);
    }
    .btn-outline-secondary:hover {
        background-color: var(--kaauh-teal-dark);
        color: white;
        border-color: var(--kaauh-teal-dark);
    }

    /* Size Utilities (matching Bootstrap convention) */
    .btn-lg {
        padding: 0.75rem 1.5rem;
        font-size: 1.1rem;
    }
    .btn-sm {
        font-size: 0.8rem;
        padding: 0.3rem 0.6rem;
    }

    /* --- Card and Layout Styles (Matching Job List) --- */
    .card {
        border: 1px solid var(--kaauh-border);
        border-radius: 0.75rem;
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
        background-color: white;
        transition: transform 0.2s, box-shadow 0.2s;
    }

    /* Template Card Hover Effect (Consistent with job list card hover) */
    .template-card {
        height: 100%;
    }
    .template-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(0,0,0,0.1) !important;
    }

    /* Card Header Theming */
    .card-header {
        /* FIX: Use !important to override default white/light backgrounds from Bootstrap */
        background-color: var(--kaauh-teal-dark) !important;
        border-bottom: 1px solid var(--kaauh-border);
        color: white !important; /* Base color for header text */
        font-weight: 600;
        padding: 1rem 1.25rem;
        border-radius: 0.75rem 0.75rem 0 0;
    }

    /* Ensure all elements within the header are visible */
    .card-header h3 {
        color: white !important;
        font-weight: 700;
    }
    .card-header .fas {
        color: white !important;
    }
    .card-header .small {
        color: rgba(255, 255, 255, 0.7) !important;
    }

    /* Stats Theming */

    /* --- Content Styles (Stats, Description) --- */
    .stat-value {
        font-size: 1.5rem;
        font-weight: 800;
        color: var(--kaauh-teal-dark);
    }
    .stat-label {
        font-size: 0.85rem;
        color: var(--kaauh-primary-text);
        font-weight: 500;
    }
    .card-description {
        min-height: 60px;
        color: var(--kaauh-primary-text);
    }

    /* Search Input Theming */
    .form-control {
        border-radius: 0.5rem 0 0 0.5rem;
        border-color: var(--kaauh-border);
        border-radius: 0 0.5rem 0.5rem 0;
    }
    .form-control-search:focus {
        border-color: var(--kaauh-teal);
        box-shadow: 0 0 0 0.1rem rgba(0, 99, 110, 0.25);
    }
    .input-group-search .input-group-text {
        background-color: white;
        border-right: none;
        border-color: var(--kaauh-border);
        border-radius: 0.5rem 0 0 0.5rem;
    }
    .input-group-search .form-control {
        border-left: none;
    }

    /* --- Danger Outline (Delete) --- */
    .btn-outline-danger {
        --bs-btn-color: #dc3545;
        --bs-btn-border-color: #dc3545;
        --bs-btn-hover-bg: #dc3545;
        --bs-btn-hover-color: white;
    }

    /* Empty State Theming */
    .empty-state {
        text-align: center;
        padding: 3rem 1rem;
        color: var(--kaauh-primary-text);
        border: 2px dashed var(--kaauh-border);
        border-radius: 0.75rem;
        background-color: var(--kaauh-gray-light);
    }
    .empty-state i {
        font-size: 3.5rem;
        margin-bottom: 1rem;
        color: var(--kaauh-teal-dark);
    }
    .empty-state .btn-main-action .fas {
        color: white !important;
    }

    /* --- Pagination Styling (Matching Job List) --- */
    .pagination .page-item .page-link {
        color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-border);
    }
    .pagination .page-item.active .page-link {
        background-color: var(--kaauh-teal);
        border-color: var(--kaauh-teal);
        color: white;
    }
    .pagination .page-item:hover .page-link:not(.active) {
        background-color: #e9ecef;
    }
</style>

{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom border-primary">
        <h1 class="h3 mb-0 fw-bold" style="color: var(--kaauh-teal-dark); font-weight: 700;">
            <i class="fas fa-file-alt me-2"></i>{% trans "Form Templates" %}
        </h1>
        <button type="button" class="btn btn-main-action" data-bs-toggle="modal" data-bs-target="#createTemplateModal">
            <i class="fas fa-plus me-1"></i> Create New Template
        </button>
    </div>

    {# Search/Filter Area - Matching Job List Structure #}
    <div class="card mb-4 shadow-sm no-hover">
        <div class="card-body">
            <h5 class="card-title text-muted mb-3" style="font-weight: 500;">Search Templates</h5>
            <form method="get" class="row g-3 align-items-end">

                <div class="col-md-6">
                    <label for="search" class="form-label small text-muted">Search by Template Name</label>
                    <div class="input-group input-group-lg input-group-search">
                        <span class="input-group-text"><i class="fas fa-search text-muted"></i></span>
                        <input type="text" name="q" id="searchInput" class="form-control form-control-search"
                            placeholder="{% trans 'Search templates by name...' %}"
                            value="{{ query|default_if_none:'' }}">
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="filter-buttons">
                        <button type="submit" class="btn btn-main-action btn-lg">
                            <i class="fas fa-filter me-1"></i> Search
                        </button>

                        {# Show Clear button if search is active #}
                        {% if query %}
                        <a href="{% url 'form_templates_list' %}" class="btn btn-outline-danger btn-sm">
                            <i class="fas fa-times me-1"></i> Clear Search
                        </a>
                        {% endif %}
                    </div>
                </div>

            </form>
        </div>
    </div>


    {% if templates %}
        <div class="row g-4">
            {% for template in templates %}
            <div class="col-lg-4 col-md-6">
                <div class="card template-card h-100">
                    <div class="card-header ">
                        <h3 class="h5 mb-2">{{ template.name }}</h3>
                        <span><i class="fas fa-sync-alt me-1"></i> {{ template.job }}</span>
                        <div class="d-flex justify-content-between text-muted small">
                            <span><i class="fas fa-calendar me-1"></i> {{ template.created_at|date:"M d, Y" }}</span>
                            <span><i class="fas fa-sync-alt me-1"></i> {{ template.updated_at|timesince }} {% trans "ago" %}</span>
                        </div>
                    </div>
                    <div class="card-body d-flex flex-column">

                        {# Content area - includes stats and description #}
                        <div class="flex-grow-1">
                            <div class="row text-center mb-3">
                                <div class="col-6">
                                    <div class="stat-value">{{ template.get_stage_count }}</div>
                                    <div class="stat-label">{% trans "Stages" %}</div>
                                </div>
                                <div class="col-6">
                                    <div class="stat-value">{{ template.get_field_count }}</div>
                                    <div class="stat-label">{% trans "Fields" %}</div>
                                </div>
                            </div>
                            <p class="card-text card-description small">
                                {% if template.description %}
                                    {{ template.description|truncatewords:20 }}
                                {% else %}
                                    <em class="text-muted">{% trans "No description provided" %}</em>
                                {% endif %}
                            </p>
                        </div>

                        {# Action area - visually separated with pt-2 border-top #}
                        <div class="mt-auto pt-2 border-top">
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">

                                <a href="{% url 'form_wizard' template.id %}" class="btn btn-outline-secondary btn-sm action-btn">
                                    <i class="fas fa-eye me-1"></i> {% trans "Preview" %}
                                </a>
                                <a href="{% url 'form_builder' template.id %}" class="btn btn-outline-secondary btn-sm action-btn">
                                    <i class="fas fa-edit me-1"></i> {% trans "Edit" %}
                                </a>
                                <button class="btn btn-outline-danger btn-sm action-btn delete"
                                        data-template-id="{{ template.id }}"
                                        data-template-name="{{ template.name }}">
                                    <i class="fas fa-trash me-1"></i> {% trans "Delete" %}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        {% if templates.has_other_pages %}
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                {# Previous page logic #}
                {% if templates.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page=1{% if query %}&q={{ query }}{% endif %}">First</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ templates.previous_page_number }}{% if query %}&q={{ query }}{% endif %}">Previous</a>
                    </li>
                {% endif %}

                {# Current Page #}
                <li class="page-item active">
                    <span class="page-link">{{ templates.number }} of {{ templates.paginator.num_pages }}</span>
                </li>

                {# Next page logic #}
                {% if templates.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ templates.next_page_number }}{% if query %}&q={{ query }}{% endif %}">Next</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ templates.paginator.num_pages }}{% if query %}&q={{ query }}{% endif %}">Last</a>
                    </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    {% else %}
        <div class="text-center py-5 card shadow-sm">
            <div class="card-body">
                <i class="fas fa-file-contract fa-3x mb-3" style="color: var(--kaauh-teal-dark);"></i>
                <h3 class="h4 mb-3">{% trans "No Form Templates Found" %}</h3>
                <p class="text-muted">
                    {% if query %}
                        {% blocktrans with query=query %}No templates match your search "{{ query }}".{% endblocktrans %}
                    {% else %}
                        {% trans "You haven't created any form templates yet." %}
                    {% endif %}
                </p>
                <a href="{% url 'form_builder' %}" class="btn btn-main-action mt-3">
                    <i class="fas fa-plus me-1 text-white"></i> {% trans "Create Your First Template" %}
                </a>
            </div>
        </div>
    {% endif %}
</div>

{% include 'includes/delete_modal.html' %}

<!-- Create Template Modal -->
<div class="modal fade" id="createTemplateModal" tabindex="-1" aria-labelledby="createTemplateModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createTemplateModalLabel">
                    <i class="fas fa-file-alt me-2"></i>Create New Form Template
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="createTemplateForm" method="post" action="{% url 'create_form_template' %}">
                    {% csrf_token %}
                    {{form|crispy}}
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="createTemplateForm" class="btn btn-primary">
                    <i class="fas fa-save me-1"></i>Create Template
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block customJS %}
<script>
    // JS logic remains the same as previous versions but ensures Django variables are handled
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        document.body.appendChild(toastContainer);
    }

    function createToast(message, type = 'success') {
        const toastId = 'toast-' + Date.now();
        const iconClass = type === 'success' ? 'check-circle text-success' : 'exclamation-circle text-danger';
        const title = type === 'success' ? 'Success' : 'Error';
        const toastHtml = `
            <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000">
                <div class="toast-header">
                    <i class="fas fa-${iconClass} me-2"></i>
                    <strong class="me-auto">${title}</strong>
                    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        `;

        toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement);
        toast.show();

        toastElement.addEventListener('hidden.bs.toast', () => {
            toastElement.remove();
        });
    }

    // Search functionality - handles submission on Enter key
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const query = this.value;
            // Assumes 'form_templates_list' is the view name for this page
            window.location.href = query ? `?q=${encodeURIComponent(query)}` : '{% url "form_templates_list" %}';
        }
    });

    // Bind search form submit to the main button click event for consistency
    document.querySelector('.filter-buttons button[type="submit"]').addEventListener('click', function(e) {
        // Prevent default submission to handle URL construction correctly
        e.preventDefault();
        const query = document.getElementById('searchInput').value;
        window.location.href = query ? `?q=${encodeURIComponent(query)}` : '{% url "form_templates_list" %}';
    });


    // Delete modal functionality
    let templateToDelete = null;

    document.querySelectorAll('.delete').forEach(button => {
        button.addEventListener('click', function() {
            const templateId = this.dataset.templateId;
            const templateName = this.dataset.templateName;
            templateToDelete = templateId;
            document.getElementById('templateNameToDelete').textContent = templateName;
            deleteModal.show();
        });
    });

    // Handle form submission in delete modal
    document.getElementById('deleteForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        if (!templateToDelete) return;

        // This relies on 'csrfToken' being defined somewhere, which is typical for Django templates.
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        try {
            // NOTE: Update this URL to match your actual Django API endpoint for deletion
            const response = await fetch(`/api/templates/${templateToDelete}/delete/`, {
                method: 'DELETE',
                headers: {
                    'X-CSRFToken': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json'
                }
            });

            const result = await response.json();

            if (result.success) {
                createToast(result.message);
                deleteModal.hide();

                // Smoothly remove the card
                setTimeout(() => {
                    const buttonClicked = document.querySelector(`button[data-template-id="${templateToDelete}"]`);
                    if(buttonClicked) {
                        const cardToRemove = buttonClicked.closest('.col-lg-4');
                        if (cardToRemove) {
                            cardToRemove.style.transition = 'opacity 0.3s ease-out, transform 0.3s ease-out';
                            cardToRemove.style.opacity = '0';
                            cardToRemove.style.transform = 'scale(0.8)';

                            setTimeout(() => {
                                cardToRemove.remove();

                                // Reload if the last card is removed to show the empty state
                                const remainingCards = document.querySelectorAll('.col-lg-4');
                                if (remainingCards.length === 0) {
                                    window.location.reload();
                                }
                            }, 300);
                        }
                    }
                }, 100);
            } else {
                createToast('Error: ' + (result.error || 'Could not delete template.'), 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            createToast('An error occurred while deleting the template.', 'error');
        }

        templateToDelete = null;
    });

    // Handle modal close event
    document.getElementById('deleteModal').addEventListener('hidden.bs.modal', function() {
        templateToDelete = null;
    });

    // Handle create template form submission
    document.getElementById('createTemplateForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const form = e.target;
        const formData = new FormData(form);

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                }
            });

            const result = await response.json();

            if (response.ok && result.success) {
                // Show success toast
                createToast(result.message || 'Template created successfully!');

                // Close modal
                bootstrap.Modal.getInstance(document.getElementById('createTemplateModal')).hide();

                // Clear form
                form.reset();

                // Redirect to form builder with new template ID
                if (result.template_id) {
                    window.location.href = `{% url 'form_builder' %}${result.template_id}/`;
                } else {
                    // Fallback to template list if no ID is returned
                    window.location.reload();
                }
            } else {
                // Show error toast
                createToast('Error: ' + (result.message || 'Could not create template.'), 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            createToast('An error occurred while creating the template.', 'error');
        }
    });
</script>
{% endblock %}
