{% extends "admin/base.html" %}
{% load i18n %}
{% block content %}
<div class="portal-v4-page k4w-monitor-center">
  <section class="portal-v4-hero portal-monitor-hero">
    <div>
      <span class="portal-eyebrow">V9.2 · DISPONIBILIDADE E INCIDENTES</span>
      <h1>Centro de monitorização</h1>
      <p>Acompanhe websites, tempos de resposta, certificados SSL e incidentes automáticos numa única área operacional.</p>
      <div class="portal-monitor-meta">
        <span><i></i> Atualizado em {{ checked_at|date:"d/m/Y H:i" }}</span>
        <span>{{ uptime_24h|default:"—" }}% de disponibilidade nas últimas 24 horas</span>
      </div>
    </div>
    <div class="portal-v4-actions">
      <button type="button" id="run-due-monitors"><span class="material-symbols-outlined">play_circle</span>Executar monitores vencidos</button>
      <a href="{% url 'admin:monitoring_websitemonitor_add' %}"><span class="material-symbols-outlined">add_monitor</span>Novo monitor</a>
      <a href="{% url 'admin:monitoring_monitorincident_changelist' %}"><span class="material-symbols-outlined">crisis_alert</span>Ver incidentes</a>
    </div>
  </section>

  <div class="portal-v4-kpis portal-monitor-kpis">
    <a href="{% url 'admin:monitoring_websitemonitor_changelist' %}"><span class="material-symbols-outlined">monitor_heart</span><small>Monitores</small><strong>{{ counts.total }}</strong></a>
    <a class="is-success" href="{% url 'admin:monitoring_websitemonitor_changelist' %}?status=up"><span class="material-symbols-outlined">check_circle</span><small>Operacionais</small><strong>{{ counts.up }}</strong></a>
    <a class="is-warning" href="{% url 'admin:monitoring_websitemonitor_changelist' %}?status=degraded"><span class="material-symbols-outlined">speed</span><small>Degradados</small><strong>{{ counts.degraded }}</strong></a>
    <a class="is-danger" href="{% url 'admin:monitoring_websitemonitor_changelist' %}?status=down"><span class="material-symbols-outlined">cloud_off</span><small>Indisponíveis</small><strong>{{ counts.down }}</strong></a>
  </div>

  <div class="portal-monitor-summary">
    <article><span class="material-symbols-outlined">query_stats</span><div><small>Uptime 24h</small><strong>{% if uptime_24h is not None %}{{ uptime_24h }}%{% else %}Sem dados{% endif %}</strong></div></article>
    <article><span class="material-symbols-outlined">speed</span><div><small>Resposta média 24h</small><strong>{{ average_response }} ms</strong></div></article>
    <article><span class="material-symbols-outlined">crisis_alert</span><div><small>Incidentes ativos</small><strong>{{ counts.incidents }}</strong></div></article>
  </div>

  <div class="portal-v4-grid portal-v4-grid-2">
    <section class="portal-v4-panel">
      <header><div><span>ESTADO ATUAL</span><h2>Websites monitorizados</h2></div><a href="{% url 'admin:monitoring_websitemonitor_changelist' %}">Ver todos</a></header>
      <div class="portal-monitor-table">
        {% for monitor in monitors %}
        <article data-monitor="{{ monitor.pk }}" class="is-{{ monitor.status }}">
          <div class="portal-monitor-status-dot"></div>
          <div class="portal-monitor-identity">
            <strong>{{ monitor.name }}</strong>
            <small>{{ monitor.technical_asset.service.client }} · {{ monitor.url }}</small>
          </div>
          <div><small>HTTP</small><b class="monitor-http">{{ monitor.last_http_status|default:"—" }}</b></div>
          <div><small>Resposta</small><b class="monitor-time">{% if monitor.last_response_ms %}{{ monitor.last_response_ms }} ms{% else %}—{% endif %}</b></div>
          <span class="portal-monitor-label">{{ monitor.get_status_display }}</span>
          <button type="button" class="run-one-monitor" data-id="{{ monitor.pk }}" title="Executar agora"><span class="material-symbols-outlined">play_arrow</span></button>
        </article>
        {% empty %}<p class="portal-v4-empty">Ainda não existem monitores configurados.</p>{% endfor %}
      </div>
    </section>

    <section class="portal-v4-panel portal-v4-panel-danger">
      <header><div><span>INCIDENTES</span><h2>Intervenções ativas</h2></div><a href="{% url 'admin:monitoring_monitorincident_changelist' %}">Histórico</a></header>
      <div class="portal-v4-list">
        {% for incident in open_incidents %}
        <a href="{% url 'admin:monitoring_monitorincident_change' incident.pk %}">
          <i class="material-symbols-outlined">{% if incident.severity == 'critical' %}error{% else %}warning{% endif %}</i>
          <div><strong>{{ incident.monitor.name }}</strong><small>{{ incident.monitor.technical_asset.service.client }} · {{ incident.reason|truncatechars:90 }}</small></div>
          <b>{{ incident.opened_at|timesince }}</b>
        </a>
        {% empty %}<p class="portal-v4-empty">Não existem incidentes ativos.</p>{% endfor %}
      </div>
    </section>
  </div>

  <section class="portal-v4-panel">
    <header><div><span>HISTÓRICO RECENTE</span><h2>Últimas verificações</h2></div><a href="{% url 'admin:monitoring_monitorcheck_changelist' %}">Abrir histórico</a></header>
    <div class="portal-monitor-history">
      {% for check in recent_checks %}
      <a href="{% url 'admin:monitoring_monitorcheck_change' check.pk %}" class="is-{{ check.result }}">
        <span class="material-symbols-outlined">{% if check.result == 'up' %}check_circle{% elif check.result == 'degraded' %}speed{% elif check.result == 'down' %}cancel{% else %}pause_circle{% endif %}</span>
        <div><strong>{{ check.monitor.name }}</strong><small>{{ check.checked_at|date:"d/m/Y H:i:s" }}{% if check.error_message %} · {{ check.error_message|truncatechars:80 }}{% endif %}</small></div>
        <b>HTTP {{ check.http_status|default:"—" }}</b><b>{% if check.response_time_ms %}{{ check.response_time_ms }} ms{% else %}—{% endif %}</b>
      </a>
      {% empty %}<p class="portal-v4-empty">Ainda não existem verificações.</p>{% endfor %}
    </div>
  </section>
</div>
<script>
(function(){
  const csrf='{{ csrf_token }}';
  const endpoint='{% url "monitoring_run" %}';
  const statusClass=(status)=>`is-${status}`;
  async function execute(data, button){
    const original=button.innerHTML; button.disabled=true; button.classList.add('is-running');
    if(button.classList.contains('run-one-monitor')) button.innerHTML='<span class="material-symbols-outlined">sync</span>';
    try{
      const body=new URLSearchParams(data);
      const response=await fetch(endpoint,{method:'POST',headers:{'X-CSRFToken':csrf,'X-Requested-With':'XMLHttpRequest','Content-Type':'application/x-www-form-urlencoded'},body});
      const result=await response.json();
      if(!response.ok || !result.ok) throw new Error(result.error||'Falha na monitorização');
      if(result.monitor_id){
        const row=document.querySelector(`[data-monitor="${result.monitor_id}"]`);
        if(row){
          row.className=statusClass(result.status);
          row.querySelector('.portal-monitor-label').textContent=result.status_label;
          row.querySelector('.monitor-http').textContent=result.http_status||'—';
          row.querySelector('.monitor-time').textContent=result.response_time_ms?`${result.response_time_ms} ms`:'—';
        }
      } else { window.location.reload(); }
    }catch(error){ alert(error.message); }
    finally{button.disabled=false;button.classList.remove('is-running');button.innerHTML=original;}
  }
  document.getElementById('run-due-monitors').addEventListener('click',function(){execute({},this)});
  document.querySelectorAll('.run-one-monitor').forEach(button=>button.addEventListener('click',function(){execute({monitor_id:this.dataset.id},this)}));
})();
</script>
{% endblock %}
