{% extends "modern/base.html" %}

{% block title %}Templates - Zebra Day{% endblock %}

{% block content %}
<div class="page-header">
    <h1 class="page-title">Shared Templates</h1>
    <p class="page-subtitle">Manage TapDB template records and label-profile defaults.</p>
</div>

<div class="grid grid-2">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Template Inventory</h3>
            <span class="badge">{{ template_names | length }}</span>
        </div>
        {% if template_names %}
        <div class="table-container" style="box-shadow:none;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {% for template_name in template_names %}
                    <tr>
                        <td><strong>{{ template_name }}</strong></td>
                        <td>
                            <button class="btn btn-sm btn-outline" onclick="loadTemplate('{{ template_name }}')">Open</button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="empty-state">
            <i class="fas fa-file-code"></i>
            <p>No templates stored in TapDB yet.</p>
        </div>
        {% endif %}
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Label Profiles</h3>
            <span class="badge">{{ label_profiles | length }}</span>
        </div>
        {% if label_profiles %}
        <div class="table-container" style="box-shadow:none;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Profile</th>
                        <th>Template</th>
                    </tr>
                </thead>
                <tbody>
                    {% for profile in label_profiles %}
                    <tr>
                        <td><strong>{{ profile.profile_name }}</strong></td>
                        <td>{{ profile.template_name or "unbound" }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="empty-state">
            <i class="fas fa-layer-group"></i>
            <p>No label profiles stored in TapDB yet.</p>
        </div>
        {% endif %}
    </div>
</div>

<div class="card mt-lg">
    <div class="card-header">
        <h3 class="card-title">Edit Template</h3>
    </div>
    <form id="template-form">
        <div class="form-group">
            <label class="form-label">Template Name</label>
            <input id="template-name" class="form-control" placeholder="tube_2inX1in" required>
        </div>
        <div class="form-group">
            <label class="form-label">ZPL Content</label>
            <textarea id="template-zpl" class="form-control" rows="14" placeholder="^XA^FO30,30^FDHello^FS^XZ" required></textarea>
        </div>
        <div class="d-flex" style="gap:var(--spacing-md);">
            <button type="submit" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-outline" onclick="deleteTemplate()">Delete</button>
            <button type="button" class="btn btn-outline" onclick="previewTemplate()">Preview PNG</button>
        </div>
    </form>
    <p class="text-muted mt-md">This editor writes directly to TapDB through the same API contract used by downstream Python clients.</p>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
async function loadTemplate(name) {
    showLoading('Loading template...');
    try {
        const response = await fetch(`/api/v1/templates/${encodeURIComponent(name)}`);
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Load failed', payload.detail || 'Unknown error');
            return;
        }
        document.getElementById('template-name').value = payload.template_name;
        document.getElementById('template-zpl').value = payload.zpl_content;
    } catch (error) {
        hideLoading();
        showToast('error', 'Load failed', error.message || 'Unknown error');
    }
}

document.getElementById('template-form')?.addEventListener('submit', async (event) => {
    event.preventDefault();
    const filename = document.getElementById('template-name').value.trim();
    const zplContent = document.getElementById('template-zpl').value;
    showLoading('Saving template...');
    try {
        const response = await fetch('/api/v1/templates', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({filename, zpl_content: zplContent}),
        });
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Save failed', payload.detail || 'Unknown error');
            return;
        }
        showToast('success', 'Saved', `Template ${payload.template_name} saved.`);
        window.location.reload();
    } catch (error) {
        hideLoading();
        showToast('error', 'Save failed', error.message || 'Unknown error');
    }
});

async function deleteTemplate() {
    const name = document.getElementById('template-name').value.trim();
    if (!name) {
        showToast('error', 'Missing name', 'Load or enter a template first.');
        return;
    }
    showLoading('Deleting template...');
    try {
        const response = await fetch(`/api/v1/templates/${encodeURIComponent(name)}`, {method: 'DELETE'});
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Delete failed', payload.detail || 'Unknown error');
            return;
        }
        showToast('success', 'Deleted', `Template ${name} deleted.`);
        window.location.reload();
    } catch (error) {
        hideLoading();
        showToast('error', 'Delete failed', error.message || 'Unknown error');
    }
}

async function previewTemplate() {
    const name = document.getElementById('template-name').value.trim();
    const zplContent = document.getElementById('template-zpl').value;
    if (!name && !zplContent) {
        showToast('error', 'Missing content', 'Load or enter a template first.');
        return;
    }
    showLoading('Rendering preview...');
    try {
        const response = await fetch('/api/v1/render', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({template: name || null, zpl_content: zplContent || null}),
        });
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Preview failed', payload.detail || 'Unknown error');
            return;
        }
        window.open(payload.png_url, '_blank');
    } catch (error) {
        hideLoading();
        showToast('error', 'Preview failed', error.message || 'Unknown error');
    }
}
</script>
{% endblock %}
