<x-app-layout>
    <x-slot name="title">Alertas de Potencia</x-slot>
    <x-slot name="breadcrumb">
        <span class="text-gray-400">Alertas de Potencia Óptica</span>
    </x-slot>

    <div class="mb-6">
        <div class="flex items-center justify-between flex-wrap gap-3">
            <div>
                <h1 class="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
                    <svg class="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/>
                    </svg>
                    Alertas de Potencia
                    @if($unacknowledgedCount > 0)
                        <span class="badge-red text-xs">{{ $unacknowledgedCount }}</span>
                    @endif
                </h1>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                    ONUs con potencia óptica por debajo del umbral configurado
                </p>
            </div>
            <div class="flex items-center gap-2">
                <button onclick="runScan()" id="scanBtn" class="btn-primary btn-sm flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                    </svg>
                    Escanear Ahora
                </button>
                <button onclick="toggleSettings()" class="btn-sm border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                    Configuración
                </button>
            </div>
        </div>
    </div>

    {{-- Settings Panel (hidden by default) --}}
    <div id="settingsPanel" class="hidden card mb-5">
        <div class="card-header flex items-center justify-between">
            <span>Configuración de Umbrales</span>
            <button onclick="toggleSettings()" class="text-gray-400 hover:text-gray-600">
                <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        <div class="card-body">
            <div class="flex flex-wrap gap-4 items-end">
                <div>
                    <label class="label text-xs">Dispositivo</label>
                    <select id="settingsDevice" class="input text-sm py-1.5 min-w-56" onchange="loadDeviceSettings()">
                        <option value="">Global (todos los dispositivos)</option>
                        @foreach($devices as $device)
                            <option value="{{ $device->id }}">{{ $device->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="label text-xs">Umbral Warning (dBm)</label>
                    <input type="number" id="warningThreshold" step="0.001" value="-25.000" class="input text-sm py-1.5 w-32 font-mono">
                </div>
                <div>
                    <label class="label text-xs">Umbral Crítico (dBm)</label>
                    <input type="number" id="criticalThreshold" step="0.001" value="-28.000" class="input text-sm py-1.5 w-32 font-mono">
                </div>
                <div class="flex items-center gap-2">
                    <input type="checkbox" id="settingsActive" checked class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                    <label for="settingsActive" class="text-sm text-gray-700 dark:text-gray-300">Activo</label>
                </div>
                <button onclick="saveSettings()" class="btn-primary btn-sm">Guardar</button>
            </div>
            <p class="text-xs text-gray-400 mt-3">
                Warning: potencia menor a umbral warning. Crítico: potencia menor a umbral crítico. Valores típicos: Warning -25 dBm, Crítico -28 dBm.
            </p>
        </div>
    </div>

    {{-- Scan status --}}
    <div id="scanStatus" class="hidden mb-5">
        <div class="card p-8 text-center">
            <div class="flex flex-col items-center gap-3">
                <svg class="w-8 h-8 animate-spin text-primary-500" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                </svg>
                <p class="text-sm text-gray-500 dark:text-gray-400">Escaneando todos los puertos de las OLTs...</p>
                <p class="text-xs text-gray-400">Esto puede tomar varios minutos.</p>
            </div>
        </div>
    </div>

    {{-- Filters --}}
    <div class="card mb-5">
        <div class="card-body py-4">
            <form method="GET" class="flex flex-wrap gap-3 items-end">
                <div>
                    <label class="label text-xs">Dispositivo</label>
                    <select name="device" class="input text-sm py-1.5 min-w-48">
                        <option value="">Todos</option>
                        @foreach($devices as $device)
                            <option value="{{ $device->id }}" {{ request('device') == $device->id ? 'selected' : '' }}>{{ $device->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="label text-xs">Severidad</label>
                    <select name="severity" class="input text-sm py-1.5 min-w-32">
                        <option value="">Todas</option>
                        <option value="critical" {{ request('severity') === 'critical' ? 'selected' : '' }}>Crítico</option>
                        <option value="warning" {{ request('severity') === 'warning' ? 'selected' : '' }}>Warning</option>
                    </select>
                </div>
                <div>
                    <label class="label text-xs">Estado</label>
                    <select name="status" class="input text-sm py-1.5 min-w-36">
                        <option value="">Todos</option>
                        <option value="unacknowledged" {{ request('status') === 'unacknowledged' ? 'selected' : '' }}>Sin reconocer</option>
                        <option value="acknowledged" {{ request('status') === 'acknowledged' ? 'selected' : '' }}>Reconocidos</option>
                    </select>
                </div>
                <button type="submit" class="btn-primary btn-sm">Filtrar</button>
                <a href="{{ route('power-alerts.index') }}" class="btn-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700">Limpiar</a>
                @if($unacknowledgedCount > 0)
                    <button type="button" onclick="acknowledgeAll()" class="btn-sm border border-yellow-400 text-yellow-600 hover:bg-yellow-50 dark:hover:bg-yellow-900/20 ml-auto">
                        Reconocer Todas ({{ $unacknowledgedCount }})
                    </button>
                @endif
            </form>
        </div>
    </div>

    {{-- Alerts table --}}
    <div class="card">
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-gray-200 dark:border-gray-700 text-left text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        <th class="p-3">Severidad</th>
                        <th class="p-3">Dispositivo</th>
                        <th class="p-3">Ubicación</th>
                        <th class="p-3">Serial</th>
                        <th class="p-3">OLT Rx</th>
                        <th class="p-3">ONU Rx</th>
                        <th class="p-3">Fecha</th>
                        <th class="p-3">Estado</th>
                        <th class="p-3 text-center">Acción</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 dark:divide-gray-700/50">
                    @forelse($alerts as $alert)
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/30 {{ !$alert->acknowledged ? 'bg-red-50/30 dark:bg-red-900/5' : '' }}" id="alert-{{ $alert->id }}">
                            <td class="p-3">
                                @if($alert->severity === 'critical')
                                    <span class="badge-red">Crítico</span>
                                @else
                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400">Warning</span>
                                @endif
                            </td>
                            <td class="p-3 text-gray-700 dark:text-gray-300">{{ $alert->device->name ?? '—' }}</td>
                            <td class="p-3 font-mono text-gray-900 dark:text-white">{{ $alert->location }}</td>
                            <td class="p-3 font-mono text-gray-600 dark:text-gray-400">{{ $alert->serial_number ?? '—' }}</td>
                            <td class="p-3 font-mono">
                                @if($alert->olt_rx_power !== null)
                                    @php $val = (float) $alert->olt_rx_power; @endphp
                                    <span class="{{ $val < -28 ? 'text-red-500' : ($val < -25 ? 'text-yellow-500' : 'text-accent-600 dark:text-accent-400') }}">
                                        {{ number_format($val, 3) }} dBm
                                    </span>
                                @else
                                    <span class="text-gray-400">N/A</span>
                                @endif
                            </td>
                            <td class="p-3 font-mono">
                                @if($alert->onu_rx_power !== null)
                                    <span class="text-gray-700 dark:text-gray-300">{{ number_format((float)$alert->onu_rx_power, 3) }} dBm</span>
                                @else
                                    <span class="text-gray-400">N/A</span>
                                @endif
                            </td>
                            <td class="p-3 text-xs text-gray-500">{{ $alert->created_at->format('d/m/y h:i A') }}</td>
                            <td class="p-3">
                                @if($alert->acknowledged)
                                    <span class="text-xs text-gray-400">Reconocido</span>
                                @else
                                    <span class="text-xs text-red-500 font-medium">Pendiente</span>
                                @endif
                            </td>
                            <td class="p-3 text-center">
                                @if(!$alert->acknowledged)
                                    <button onclick="acknowledgeOne({{ $alert->id }})" class="text-xs text-primary-600 hover:text-primary-800 dark:text-primary-400 hover:underline">
                                        Reconocer
                                    </button>
                                @else
                                    <span class="text-xs text-gray-300">—</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9" class="p-12 text-center">
                                <div class="flex flex-col items-center gap-3 text-gray-400">
                                    <svg class="w-12 h-12 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                    </svg>
                                    <p class="text-sm">No hay alertas registradas</p>
                                    <p class="text-xs">Ejecuta un escaneo o configura el comando programado <code class="bg-gray-100 dark:bg-gray-700 px-1 rounded">php artisan olt:check-power</code></p>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($alerts->hasPages())
            <div class="p-4 border-t border-gray-100 dark:border-gray-700">
                {{ $alerts->links() }}
            </div>
        @endif
    </div>

    <script>
    const baseUrl   = '{{ url("/") }}';
    const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    const headers   = { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' };

    function toggleSettings() {
        document.getElementById('settingsPanel').classList.toggle('hidden');
    }

    async function loadDeviceSettings() {
        try {
            const resp = await fetch(`${baseUrl}/power-alerts/settings`, { headers: { 'Accept': 'application/json' } });
            const data = await resp.json();
            if (!data.success) return;

            const deviceId = document.getElementById('settingsDevice').value;
            let s = data.global;
            if (deviceId && data.settings[deviceId]) {
                s = data.settings[deviceId];
            }
            document.getElementById('warningThreshold').value = s.warning_threshold;
            document.getElementById('criticalThreshold').value = s.critical_threshold;
            document.getElementById('settingsActive').checked = s.active;
        } catch(e) {
            console.error('Error loading settings:', e);
        }
    }

    async function saveSettings() {
        const deviceId = document.getElementById('settingsDevice').value;
        try {
            const resp = await fetch(`${baseUrl}/power-alerts/settings`, {
                method: 'POST',
                headers,
                body: JSON.stringify({
                    device_id: deviceId || null,
                    warning_threshold: parseFloat(document.getElementById('warningThreshold').value),
                    critical_threshold: parseFloat(document.getElementById('criticalThreshold').value),
                    active: document.getElementById('settingsActive').checked,
                })
            });
            const data = await resp.json();
            if (data.success) {
                alert('Configuración guardada.');
            } else {
                alert('Error: ' + (data.message || 'Error desconocido'));
            }
        } catch(e) {
            alert('Error: ' + e.message);
        }
    }

    async function runScan() {
        const btn = document.getElementById('scanBtn');
        btn.disabled = true;
        document.getElementById('scanStatus').classList.remove('hidden');

        try {
            const controller = new AbortController();
            setTimeout(() => controller.abort(), 600000); // 10 min timeout
            const resp = await fetch(`${baseUrl}/power-alerts/scan`, { method: 'POST', headers, signal: controller.signal });
            const data = await resp.json();
            document.getElementById('scanStatus').classList.add('hidden');

            if (data.success) {
                alert('Escaneo completado.\n' + (data.output || ''));
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        } catch(e) {
            document.getElementById('scanStatus').classList.add('hidden');
            alert('Error: ' + e.message);
        } finally {
            btn.disabled = false;
        }
    }

    async function acknowledgeOne(id) {
        try {
            const resp = await fetch(`${baseUrl}/power-alerts/${id}/acknowledge`, { method: 'POST', headers });
            const data = await resp.json();
            if (data.success) {
                const row = document.getElementById('alert-' + id);
                if (row) {
                    row.classList.remove('bg-red-50/30', 'dark:bg-red-900/5');
                    row.querySelectorAll('td')[7].innerHTML = '<span class="text-xs text-gray-400">Reconocido</span>';
                    row.querySelectorAll('td')[8].innerHTML = '<span class="text-xs text-gray-300">—</span>';
                }
            }
        } catch(e) {
            alert('Error: ' + e.message);
        }
    }

    async function acknowledgeAll() {
        if (!confirm('¿Reconocer todas las alertas pendientes?')) return;
        try {
            const params = new URLSearchParams(window.location.search);
            const body = {};
            if (params.get('device')) body.device = params.get('device');

            const resp = await fetch(`${baseUrl}/power-alerts/acknowledge-all`, { method: 'POST', headers, body: JSON.stringify(body) });
            const data = await resp.json();
            if (data.success) {
                alert(`${data.count} alertas reconocidas.`);
                location.reload();
            }
        } catch(e) {
            alert('Error: ' + e.message);
        }
    }
    </script>
</x-app-layout>
