{% extends "base.html" %}

{% block title %}Drucker bearbeiten - MYP Admin{% endblock %}

{% block extra_css %}
<!-- Zusätzliche Styles für diese Seite -->
<style>
    .form-container {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    }
    
    .dark .form-container {
        background: rgba(30, 41, 59, 0.95);
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen py-8">
    <div class="max-w-2xl mx-auto px-4">
        <!-- Header -->
        <div class="form-container rounded-lg p-6 mb-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-edit text-blue-600 dark:text-blue-400 text-2xl"></i>
                    <h1 class="text-2xl font-bold text-slate-800 dark:text-white">Drucker bearbeiten</h1>
                </div>
                <a href="{{ url_for('admin_page', tab='printers') }}" 
                   class="bg-slate-500 hover:bg-slate-600 text-white px-4 py-2 rounded-lg transition-colors">
                    <i class="fas fa-arrow-left mr-2"></i>Zurück
                </a>
            </div>
            <div class="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <p class="text-sm text-blue-700 dark:text-blue-300">
                    <i class="fas fa-info-circle mr-2"></i>
                    <strong>Drucker-ID:</strong> {{ printer.id }} | 
                    <strong>Erstellt am:</strong> {{ printer.created_at[:10] if printer.created_at else 'Unbekannt' }}
                </p>
            </div>
        </div>

        <!-- Formular -->
        <div class="form-container rounded-lg p-6">
            <form action="{{ url_for('admin_update_printer_form', printer_id=printer.id) }}" method="POST" class="space-y-6">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                
                <!-- Name -->
                <div>
                    <label for="name" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-tag mr-2"></i>Drucker-Name *
                    </label>
                    <input type="text" 
                           id="name" 
                           name="name" 
                           required 
                           value="{{ printer.name }}"
                           class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                           placeholder="3D-Drucker Raum A001">
                </div>

                <!-- IP-Adresse -->
                <div>
                    <label for="ip_address" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-network-wired mr-2"></i>IP-Adresse *
                    </label>
                    <input type="text" 
                           id="ip_address" 
                           name="ip_address" 
                           required 
                           value="{{ printer.plug_ip }}"
                           pattern="^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
                           class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                           placeholder="192.168.1.100">
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">IP-Adresse der Tapo-Steckdose</p>
                </div>

                <!-- Modell -->
                <div>
                    <label for="model" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-cogs mr-2"></i>Drucker-Modell
                    </label>
                    <input type="text" 
                           id="model" 
                           name="model" 
                           value="{{ printer.model }}"
                           class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                           placeholder="Ender 3 V2">
                </div>

                <!-- Standort -->
                <div>
                    <label for="location" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-map-marker-alt mr-2"></i>Standort
                    </label>
                    <input type="text" 
                           id="location" 
                           name="location" 
                           value="{{ printer.location }}"
                           class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                           placeholder="Raum A001, Erdgeschoss">
                </div>

                <!-- Beschreibung -->
                <div>
                    <label for="description" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-comment mr-2"></i>Beschreibung
                    </label>
                    <textarea id="description" 
                              name="description" 
                              rows="3"
                              class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                              placeholder="Zusätzliche Informationen zum Drucker...">{{ printer.description or '' }}</textarea>
                </div>

                <!-- Status -->
                <div>
                    <label for="status" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                        <i class="fas fa-circle mr-2"></i>Aktueller Status
                    </label>
                    <select id="status" 
                            name="status" 
                            class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-slate-900 dark:text-white">
                        <option value="available" {{ 'selected' if printer.status == 'available' else '' }}>Verfügbar</option>
                        <option value="offline" {{ 'selected' if printer.status == 'offline' else '' }}>Offline</option>
                        <option value="maintenance" {{ 'selected' if printer.status == 'maintenance' else '' }}>Wartung</option>
                        <option value="online" {{ 'selected' if printer.status == 'online' else '' }}>Online</option>
                        <option value="printing" {{ 'selected' if printer.status == 'printing' else '' }}>Druckt</option>
                    </select>
                </div>

                <!-- Aktiv-Status -->
                <div>
                    <label class="flex items-center space-x-3">
                        <input type="checkbox" 
                               name="is_active" 
                               {{ 'checked' if printer.active else '' }}
                               class="w-4 h-4 text-blue-600 bg-slate-100 dark:bg-slate-700 border-slate-300 dark:border-slate-600 rounded focus:ring-blue-500 focus:ring-2">
                        <span class="text-sm font-medium text-slate-700 dark:text-slate-300">
                            <i class="fas fa-power-off mr-2"></i>Drucker aktiv
                        </span>
                    </label>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Inaktive Drucker werden nicht für neue Aufträge verwendet</p>
                </div>

                <!-- Erweiterte Informationen -->
                <div class="bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 rounded-lg p-4">
                    <h3 class="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-3">
                        <i class="fas fa-info-circle mr-2"></i>Drucker-Informationen
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                        <div>
                            <span class="font-medium text-slate-600 dark:text-slate-400">MAC-Adresse:</span>
                            <span class="text-slate-800 dark:text-slate-200">{{ printer.mac_address or 'Nicht verfügbar' }}</span>
                        </div>
                        <div>
                            <span class="font-medium text-slate-600 dark:text-slate-400">Letzter Check:</span>
                            <span class="text-slate-800 dark:text-slate-200">{{ printer.last_checked or 'Nie' }}</span>
                        </div>
                    </div>
                </div>

                <!-- Warnung -->
                <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-500 dark:text-yellow-400 mt-0.5 mr-3"></i>
                        <div class="text-sm text-yellow-700 dark:text-yellow-300">
                            <p class="font-semibold mb-1">Wichtige Hinweise:</p>
                            <ul class="list-disc list-inside space-y-1">
                                <li>Änderungen an der IP-Adresse können die Verbindung unterbrechen</li>
                                <li>Stellen Sie sicher, dass die Tapo-Steckdose unter der neuen IP erreichbar ist</li>
                                <li>Bei Status-Änderungen werden laufende Jobs möglicherweise beeinflusst</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Aktionen -->
                <div class="flex space-x-3 pt-4">
                    <button type="submit" 
                            class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
                        <i class="fas fa-save mr-2"></i>Änderungen speichern
                    </button>
                    <a href="{{ url_for('admin_page', tab='printers') }}" 
                       class="flex-1 bg-slate-500 hover:bg-slate-600 text-white px-4 py-2 rounded-lg text-center transition-colors">
                        <i class="fas fa-times mr-2"></i>Abbrechen
                    </a>
                </div>
            </form>
        </div>

        <!-- Zusätzliche Aktionen -->
        <div class="form-container rounded-lg p-6 mt-6">
            <h3 class="text-lg font-semibold text-slate-800 dark:text-white mb-4">
                <i class="fas fa-tools mr-2"></i>Drucker-Aktionen
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <button data-printer-id="{{ printer.id }}" 
                        data-action="test"
                        class="printer-action-btn bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-lg transition-colors">
                    <i class="fas fa-plug mr-2"></i>Verbindung testen
                </button>
                <button data-printer-id="{{ printer.id }}" 
                        data-action="toggle"
                        class="printer-action-btn bg-orange-600 hover:bg-orange-700 text-white px-4 py-3 rounded-lg transition-colors">
                    <i class="fas fa-power-off mr-2"></i>Ein/Ausschalten
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- JavaScript -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.querySelector('form');
        const nameInput = document.getElementById('name');
        const ipInput = document.getElementById('ip_address');

        // IP-Adresse-Validierung
        ipInput.addEventListener('blur', function() {
            const ip = this.value;
            const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
            
            if (ip && !ipRegex.test(ip)) {
                this.classList.add('border-red-500');
                this.classList.remove('border-slate-300', 'dark:border-slate-600');
            } else {
                this.classList.remove('border-red-500');
                this.classList.add('border-slate-300', 'dark:border-slate-600');
            }
        });

        // Form-Submit-Validierung
        form.addEventListener('submit', function(e) {
            const name = nameInput.value.trim();
            const ip = ipInput.value.trim();
            const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

            if (!name) {
                e.preventDefault();
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage('Bitte geben Sie einen Drucker-Namen ein.', 'error');
                } else {
                    alert('Bitte geben Sie einen Drucker-Namen ein.');
                }
                nameInput.focus();
                return;
            }

            if (!ip || !ipRegex.test(ip)) {
                e.preventDefault();
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage('Bitte geben Sie eine gültige IP-Adresse ein.', 'error');
                } else {
                    alert('Bitte geben Sie eine gültige IP-Adresse ein.');
                }
                ipInput.focus();
                return;
            }
        });

        // Event-Listener für Drucker-Aktions-Buttons
        document.querySelectorAll('.printer-action-btn').forEach(button => {
            button.addEventListener('click', function() {
                const printerId = this.getAttribute('data-printer-id');
                const action = this.getAttribute('data-action');
                
                if (action === 'test') {
                    testPrinterConnection(printerId, this);
                } else if (action === 'toggle') {
                    togglePrinterPower(printerId, this);
                }
            });
        });
    });

    // Verbindungstest
    function testPrinterConnection(printerId, button) {
        const originalText = button.innerHTML;
        
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Teste...';
        button.disabled = true;
        
        fetch(`/api/admin/printers/${printerId}/test-tapo`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.tapo_test && data.tapo_test.success) {
                const message = '✅ Verbindung erfolgreich!\n\nStatus: ' + (data.tapo_test.device_info ? data.tapo_test.device_info.device_on ? 'EIN' : 'AUS' : 'Unbekannt');
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage(message, 'success');
                } else {
                    alert(message);
                }
            } else {
                const message = '❌ Verbindung fehlgeschlagen!\n\nFehler: ' + (data.tapo_test ? data.tapo_test.error : 'Unbekannter Fehler');
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage(message, 'error');
                } else {
                    alert(message);
                }
            }
        })
        .catch(error => {
            const message = '❌ Verbindungstest fehlgeschlagen!\n\nFehler: ' + error.message;
            if (typeof showFlashMessage === 'function') {
                showFlashMessage(message, 'error');
            } else {
                alert(message);
            }
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }

    // Drucker ein/ausschalten
    function togglePrinterPower(printerId, button) {
        const originalText = button.innerHTML;
        
        if (!confirm('Möchten Sie den Drucker ein-/ausschalten?')) {
            return;
        }
        
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Schaltet...';
        button.disabled = true;
        
        fetch(`/api/admin/printers/${printerId}/toggle`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const message = '✅ Drucker erfolgreich ' + data.action + '!';
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage(message, 'success');
                } else {
                    alert(message);
                }
                // Seite neu laden um aktuellen Status zu zeigen
                setTimeout(() => location.reload(), 1000);
            } else {
                const message = '❌ Fehler beim Schalten!\n\nFehler: ' + (data.error || 'Unbekannter Fehler');
                if (typeof showFlashMessage === 'function') {
                    showFlashMessage(message, 'error');
                } else {
                    alert(message);
                }
            }
        })
        .catch(error => {
            const message = '❌ Schaltvorgang fehlgeschlagen!\n\nFehler: ' + error.message;
            if (typeof showFlashMessage === 'function') {
                showFlashMessage(message, 'error');
            } else {
                alert(message);
            }
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }
</script>
{% endblock %} 