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

{% block title %}Print Label - Zebra Day{% endblock %}

{% block content %}
<div class="page-header">
    <h1 class="page-title">Print Label</h1>
    <p class="page-subtitle">Resolve shared printer defaults from zebra_day, then preview or print.</p>
</div>

<form id="print-form">
    <div class="grid grid-2">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Printer</h3>
            </div>
            <div class="form-group">
                <label class="form-label required">Lab</label>
                <select id="lab-select" name="lab" class="form-control" required>
                    <option value="">Select a lab...</option>
                    {% for lab_name in labs %}
                    <option value="{{ lab_name }}" {% if selected_lab == lab_name %}selected{% endif %}>{{ lab_name.replace('-', ' ').title() }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label class="form-label required">Printer</label>
                <select id="printer-select" name="printer" class="form-control" required>
                    <option value="">Select a printer...</option>
                </select>
            </div>
            <div class="form-group mb-0">
                <label class="form-label">Template or Profile</label>
                <select id="template-select" name="label_zpl_style" class="form-control">
                    <option value="">Use printer default</option>
                    {% for template_name in template_names %}
                    <option value="{{ template_name }}" {% if selected_template == template_name %}selected{% endif %}>{{ template_name }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Payload</h3>
            </div>
            <div class="form-group">
                <label class="form-label">UID Barcode</label>
                <input type="text" name="uid_barcode" class="form-control" placeholder="UID barcode">
            </div>
            <div class="grid grid-2" style="gap: var(--spacing-md);">
                <div class="form-group">
                    <label class="form-label">Alt A</label>
                    <input type="text" name="alt_a" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Alt B</label>
                    <input type="text" name="alt_b" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Alt C</label>
                    <input type="text" name="alt_c" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Alt D</label>
                    <input type="text" name="alt_d" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Alt E</label>
                    <input type="text" name="alt_e" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Alt F</label>
                    <input type="text" name="alt_f" class="form-control">
                </div>
            </div>
            <div class="form-group mb-0">
                <label class="form-label">Copies</label>
                <input type="number" name="copies" class="form-control" value="1" min="1" max="100">
            </div>
        </div>
    </div>

    <div class="card mt-lg">
        <div class="d-flex" style="justify-content: space-between; align-items: center;">
            <a href="/" class="btn btn-outline">Cancel</a>
            <div class="d-flex" style="gap: var(--spacing-md);">
                <button type="button" class="btn btn-outline" id="resolve-btn">Resolve</button>
                <button type="button" class="btn btn-secondary" id="preview-btn">Download PNG</button>
                <button type="submit" class="btn btn-primary">Print</button>
            </div>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_scripts %}
<script>
const labsDict = {{ labs_dict | safe }};
const selectedPrinter = {{ selected_printer | tojson }};

function populatePrinters() {
    const lab = document.getElementById('lab-select').value;
    const printerSelect = document.getElementById('printer-select');
    printerSelect.innerHTML = '<option value="">Select a printer...</option>';
    const printers = labsDict?.[lab]?.printers || {};
    Object.keys(printers).sort().forEach((printerId) => {
        const printer = printers[printerId];
        const option = document.createElement('option');
        option.value = printerId;
        option.textContent = printer.printer_name || printerId;
        if (printerId === selectedPrinter) {
            option.selected = true;
        }
        printerSelect.appendChild(option);
    });
}

function formPayload() {
    const form = document.getElementById('print-form');
    const formData = new FormData(form);
    return {
        lab: formData.get('lab'),
        printer: formData.get('printer'),
        label_zpl_style: formData.get('label_zpl_style') || null,
        uid_barcode: formData.get('uid_barcode') || '',
        alt_a: formData.get('alt_a') || '',
        alt_b: formData.get('alt_b') || '',
        alt_c: formData.get('alt_c') || '',
        alt_d: formData.get('alt_d') || '',
        alt_e: formData.get('alt_e') || '',
        alt_f: formData.get('alt_f') || '',
        copies: Number(formData.get('copies') || '1'),
    };
}

async function resolvePrint() {
    showLoading('Resolving print request...');
    try {
        const response = await fetch('/api/v1/print/resolve', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(formPayload()),
        });
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Resolve failed', payload.detail || 'Unknown error');
            return;
        }
        showToast('success', 'Resolved', `${payload.printer.printer_name || payload.printer_id} -> ${payload.template_name || payload.label_style || 'printer default'}`);
    } catch (error) {
        hideLoading();
        showToast('error', 'Resolve failed', error.message || 'Unknown error');
    }
}

async function downloadPreview() {
    showLoading('Rendering PNG...');
    try {
        const payload = formPayload();
        const response = await fetch('/api/v1/render/png', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                template: payload.label_zpl_style,
                uid_barcode: payload.uid_barcode,
                alt_a: payload.alt_a,
                alt_b: payload.alt_b,
                alt_c: payload.alt_c,
                alt_d: payload.alt_d,
                alt_e: payload.alt_e,
                alt_f: payload.alt_f,
            }),
        });
        hideLoading();
        if (!response.ok) {
            const errorPayload = await response.json();
            showToast('error', 'Preview failed', errorPayload.detail || 'Unknown error');
            return;
        }
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const anchor = document.createElement('a');
        anchor.href = url;
        anchor.download = `${payload.label_zpl_style || 'label'}_preview.png`;
        document.body.appendChild(anchor);
        anchor.click();
        window.URL.revokeObjectURL(url);
        anchor.remove();
    } catch (error) {
        hideLoading();
        showToast('error', 'Preview failed', error.message || 'Unknown error');
    }
}

document.getElementById('lab-select')?.addEventListener('change', populatePrinters);
document.getElementById('resolve-btn')?.addEventListener('click', resolvePrint);
document.getElementById('preview-btn')?.addEventListener('click', downloadPreview);
document.getElementById('print-form')?.addEventListener('submit', async (event) => {
    event.preventDefault();
    showLoading('Submitting print job...');
    try {
        const response = await fetch('/api/v1/print', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(formPayload()),
        });
        const payload = await response.json();
        hideLoading();
        if (!response.ok) {
            showToast('error', 'Print failed', payload.detail || 'Unknown error');
            return;
        }
        showToast('success', 'Print submitted', payload.message || 'Print request sent.');
    } catch (error) {
        hideLoading();
        showToast('error', 'Print failed', error.message || 'Unknown error');
    }
});

document.addEventListener('DOMContentLoaded', populatePrinters);
</script>
{% endblock %}
