{% extends "base.html" %}
{% block title %}Dashboard{% endblock %}

{% block content %}

{# ── Statistiques rapides ─────────────────────────────────────────────────── #}
{% set total = jobs | length %}
{% set enabled_count = jobs | selectattr('enabled') | list | length %}
{% set recent_runs = last_runs.values() | select | list %}
{% set success_count = recent_runs | selectattr('status', 'equalto', 'success') | list | length %}
{% set warning_count = recent_runs | selectattr('status', 'equalto', 'warning') | list | length %}
{% set error_count = recent_runs | selectattr('status', 'equalto', 'error') | list | length %}
{% set running_count = recent_runs | selectattr('status', 'equalto', 'running') | list | length %}

<div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-8">
  <div class="bg-white rounded-xl border border-gray-200 px-5 py-4">
    <p class="text-xs text-gray-500 uppercase tracking-wide">Jobs</p>
    <p class="text-3xl font-bold text-gray-800 mt-1">{{ total }}</p>
    <p class="text-xs text-gray-400 mt-1">{{ enabled_count }} actifs</p>
  </div>
  <div class="bg-white rounded-xl border border-gray-200 px-5 py-4">
    <p class="text-xs text-gray-500 uppercase tracking-wide">Succès</p>
    <p class="text-3xl font-bold text-green-600 mt-1">{{ success_count }}</p>
    <p class="text-xs text-gray-400 mt-1">dernière exécution</p>
  </div>
  <div class="bg-white rounded-xl border border-gray-200 px-5 py-4">
    <p class="text-xs text-gray-500 uppercase tracking-wide">Erreurs</p>
    <p class="text-3xl font-bold {% if error_count > 0 %}text-red-600{% elif warning_count > 0 %}text-amber-500{% else %}text-gray-400{% endif %} mt-1">
      {{ error_count + warning_count }}
    </p>
    <p class="text-xs text-gray-400 mt-1">dernière exécution{% if warning_count > 0 and error_count == 0 %} (transfert partiel){% endif %}</p>
  </div>
  <div class="bg-white rounded-xl border border-gray-200 px-5 py-4">
    <p class="text-xs text-gray-500 uppercase tracking-wide">En cours</p>
    <p class="text-3xl font-bold {% if running_count > 0 %}text-blue-600{% else %}text-gray-400{% endif %} mt-1">
      {{ running_count }}
    </p>
    <p class="text-xs text-gray-400 mt-1">actuellement</p>
  </div>
</div>

{# ── Table des jobs ───────────────────────────────────────────────────────── #}
<div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
  <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
    <h2 class="text-base font-semibold text-gray-800">Jobs de sauvegarde</h2>
  </div>
  <!-- Barre actions groupées (masquée par défaut) -->
  <div id="bulk-bar" class="hidden bg-blue-50 border-b border-blue-200 px-6 py-2 flex items-center gap-3 text-sm">
    <span class="text-blue-700 font-medium"><span id="bulk-count">0</span> sélectionné(s)</span>
    <button type="button" onclick="bulkAction('run')" class="btn-primary btn-sm">▶ Lancer</button>
    <button type="button" onclick="bulkAction('enable')" class="btn-secondary btn-sm">Activer</button>
    <button type="button" onclick="bulkAction('disable')" class="btn-secondary btn-sm">Désactiver</button>
    <button type="button" onclick="bulkAction('delete', 'Supprimer les jobs sélectionnés et leur historique ?')" class="btn-danger btn-sm">✕ Supprimer</button>
  </div>

  {% if not jobs %}
    <div class="px-6 py-12 text-center text-gray-400">
      <p class="text-lg">Aucun job configuré.</p>
      <a href="{{ url_for('jobs.job_new') }}" class="mt-3 inline-block text-blue-600 hover:underline text-sm">
        Créer le premier job →
      </a>
    </div>
  {% else %}
    <div class="overflow-x-auto">
      <table class="w-full text-sm">
        <thead>
          <tr class="text-xs text-gray-500 uppercase tracking-wide bg-gray-50">
            <th class="px-4 py-3 w-8">
              <input type="checkbox" id="select-all" class="rounded border-gray-300 text-blue-600">
            </th>
            <th class="px-6 py-3 text-left font-medium">Nom</th>
            <th class="px-6 py-3 text-left font-medium">Type</th>
            <th class="px-6 py-3 text-left font-medium">Planification</th>
            <th class="px-6 py-3 text-left font-medium">Transfert</th>
            <th class="px-6 py-3 text-left font-medium">Dernière exéc.</th>
            <th class="px-6 py-3 text-left font-medium">Statut</th>
            <th class="px-6 py-3 text-left font-medium">Taille</th>
            <th class="px-6 py-3 text-right font-medium">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          {% for job in jobs %}
            {% set run = last_runs.get(job.id) %}
            <tr class="hover:bg-gray-50 {% if not job.enabled %}opacity-50{% endif %}">
              <td class="px-4 py-4">
                <input type="checkbox" class="job-checkbox rounded border-gray-300 text-blue-600" value="{{ job.id }}">
              </td>
              <td class="px-6 py-4">
                <span class="font-medium text-gray-900">{{ job.name }}</span>
                {% if job.type == 'ynh_app' and job.config_json %}
                  {% set _cfg = job.config_json | fromjson %}
                  {% set _app_id = _cfg.get('app_id') %}
                  {% if _app_id %}
                    {% set _label = ynh_app_labels.get(_app_id, '') %}
                    <br>
                    {% if _label and _label != _app_id %}
                      <span class="text-xs text-gray-500">{{ _label }}</span>
                    {% else %}
                      <span class="font-mono text-xs text-gray-400">{{ _app_id }}</span>
                    {% endif %}
                  {% endif %}
                {% endif %}
              </td>
              <td class="px-6 py-4">
                <span class="bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded font-mono">
                  {{ job.type }}
                </span>
              </td>
              <td class="px-6 py-4 font-mono text-xs text-gray-600">
                {% if job.cron_expr %}{{ job.cron_expr }}
                {% else %}<span class="bg-gray-100 text-gray-500 text-xs px-2 py-0.5 rounded font-sans">Manuel</span>{% endif %}
              </td>
              <td class="px-6 py-4">
                {% if job.job_destinations %}
                  <div class="flex flex-wrap gap-1">
                    {% for jd in job.job_destinations %}
                      {% set obj = jd.resolved %}{% if obj %}
                        {% if jd.dest_type == 'ssh' %}
                          <span class="bg-violet-50 text-violet-700 text-xs px-2 py-0.5 rounded font-medium" title="{{ obj.remote_str }}">SSH · {{ obj.name }}</span>
                        {% else %}
                          <span class="bg-blue-50 text-blue-700 text-xs px-2 py-0.5 rounded font-medium" title="{{ obj.url }}">HTTP · {{ obj.name }}</span>
                        {% endif %}
                      {% endif %}
                    {% endfor %}
                  </div>
                {% else %}
                  <span class="bg-gray-100 text-gray-500 text-xs px-2 py-0.5 rounded">Local</span>
                {% endif %}
              </td>
              <td class="px-6 py-4 text-xs text-gray-500">
                {% if run and run.started_at %}
                  {{ run.started_at.strftime('%d/%m/%Y %H:%M') }}
                {% else %}
                  <span class="text-gray-300">Jamais</span>
                {% endif %}
              </td>
              <td class="px-6 py-4">
                {% if run %}
                  {% if run.status == 'success' %}
                    <span class="bg-green-100 text-green-700 text-xs font-medium px-2 py-0.5 rounded-full">✓ succès</span>
                  {% elif run.status == 'warning' %}
                    <span class="bg-amber-100 text-amber-700 text-xs font-medium px-2 py-0.5 rounded-full">⚠ transfert partiel</span>
                  {% elif run.status == 'error' %}
                    <span class="bg-red-100 text-red-700 text-xs font-medium px-2 py-0.5 rounded-full">✗ erreur</span>
                  {% elif run.status == 'running' %}
                    <span class="bg-blue-100 text-blue-700 text-xs font-medium px-2 py-0.5 rounded-full animate-pulse">⟳ en cours</span>
                  {% endif %}
                {% else %}
                  <span class="text-gray-300 text-xs">—</span>
                {% endif %}
              </td>
              <td class="px-6 py-4 text-xs text-gray-500">
                {% if run and run.size_bytes %}{{ run.size_human }}{% else %}—{% endif %}
              </td>
              <td class="px-6 py-4 text-right">
                <div class="flex items-center justify-end gap-2">
                  <form method="post" action="{{ url_for('jobs.job_run_now', job_id=job.id) }}"
                        onsubmit="return confirm('Lancer « {{ job.name }} » maintenant ?')">
                    <button type="submit" class="btn-primary btn-sm">▶</button>
                  </form>
                  <a href="{{ url_for('jobs.job_history', job_id=job.id) }}"
                     class="btn-secondary btn-sm">Historique</a>
                  <a href="{{ url_for('jobs.job_edit', job_id=job.id) }}"
                     class="btn-secondary btn-sm">Éditer</a>
                  <form method="post" action="{{ url_for('jobs.job_toggle', job_id=job.id) }}">
                    <button type="submit" class="btn-ghost btn-icon-sm"
                      title="{{ 'Désactiver' if job.enabled else 'Activer' }}">
                      {{ '⏸' if job.enabled else '▶' }}
                    </button>
                  </form>
                  <form method="post" action="{{ url_for('jobs.job_delete', job_id=job.id) }}"
                        onsubmit="return confirm('Supprimer définitivement « {{ job.name }} » et son historique ?')">
                    <button type="submit" class="btn-danger btn-icon-sm">✕</button>
                  </form>
                </div>
              </td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  {% endif %}
</div>

{# ── Serveurs fédérés ─────────────────────────────────────────────── #}
{% if instances %}
<div class="mt-8">
  <div class="flex items-center justify-between mb-4">
    <h2 class="text-base font-semibold text-gray-700">Serveurs fédérés</h2>
    <form method="post" action="{{ url_for('network.network_sync_all') }}">
      <button type="submit" class="btn-secondary btn-sm">Synchroniser tout</button>
    </form>
  </div>

  {% for inst in instances %}
  {% set sc = {'online':'bg-green-100 text-green-700','error':'bg-red-100 text-red-700','offline':'bg-gray-100 text-gray-500'} %}
  <div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden mb-4">
    <div class="px-6 py-3 border-b border-gray-100 flex items-center justify-between gap-4">
      <div class="flex items-center gap-3">
        <span class="font-semibold text-gray-800 text-sm">{{ inst.name }}</span>
        <span class="text-xs px-2 py-0.5 rounded-full font-medium {{ sc.get(inst.status, 'bg-gray-100 text-gray-400') }}">
          {{ inst.status or 'unknown' }}
        </span>
        {% if inst.last_seen %}
          <span class="text-xs text-gray-400 hidden sm:inline">sync {{ inst.last_seen.strftime('%d/%m %H:%M') }}</span>
        {% endif %}
        <span class="text-xs font-mono text-gray-400 truncate hidden md:inline">{{ inst.url_display }}</span>
      </div>
      <div class="flex gap-2 shrink-0">
        <form method="post" action="{{ url_for('network.remote_instance_sync', inst_id=inst.id) }}">
          <button type="submit" class="btn-secondary btn-sm">Sync</button>
        </form>
      </div>
    </div>

    {% if not inst.remote_runs %}
      <div class="px-6 py-5 text-center text-gray-400 text-sm">
        Aucune donnée — cliquez sur "Sync" pour récupérer l'état.
      </div>
    {% else %}
    <div class="overflow-x-auto">
      <table class="w-full text-sm">
        <thead>
          <tr class="text-xs text-gray-500 uppercase tracking-wide bg-gray-50">
            <th class="px-6 py-3 text-left font-medium">Nom</th>
            <th class="px-6 py-3 text-left font-medium">Type</th>
            <th class="px-6 py-3 text-left font-medium">Dernière exéc.</th>
            <th class="px-6 py-3 text-left font-medium">Statut</th>
            <th class="px-6 py-3 text-left font-medium">Taille</th>
            <th class="px-6 py-3 text-right font-medium">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          {% for row in inst.remote_runs %}
          <tr class="hover:bg-gray-50">
            <td class="px-6 py-3 font-medium text-gray-900">{{ row.job_name }}</td>
            <td class="px-6 py-3">
              <span class="bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded font-mono">{{ row.job_type }}</span>
            </td>
            <td class="px-6 py-3 text-xs text-gray-500">
              {% if row.last_run_at %}{{ row.last_run_at.strftime('%d/%m/%Y %H:%M') }}
              {% else %}<span class="text-gray-300">Jamais</span>{% endif %}
            </td>
            <td class="px-6 py-3">
              {% if row.last_status == 'success' %}
                <span class="bg-green-100 text-green-700 text-xs font-medium px-2 py-0.5 rounded-full">✓ succès</span>
              {% elif row.last_status == 'error' %}
                <span class="bg-red-100 text-red-700 text-xs font-medium px-2 py-0.5 rounded-full">✗ erreur</span>
              {% elif row.last_status == 'running' %}
                <span class="bg-blue-100 text-blue-700 text-xs font-medium px-2 py-0.5 rounded-full animate-pulse">⟳ en cours</span>
              {% else %}
                <span class="text-gray-300 text-xs">—</span>
              {% endif %}
            </td>
            <td class="px-6 py-3 text-xs text-gray-500">
              {% if row.last_size_bytes %}{{ row.last_size_human }}{% else %}—{% endif %}
            </td>
            <td class="px-6 py-3 text-right">
              <div class="flex items-center justify-end gap-2">
                {% if row.job_id %}
                <form method="post"
                      action="{{ url_for('network.remote_job_run', inst_id=inst.id, job_id=row.job_id) }}"
                      onsubmit="return confirm('Lancer « {{ row.job_name }} » sur {{ inst.name }} ?')">
                  <button type="submit" class="btn-primary btn-sm">▶ Lancer</button>
                </form>
                <form method="post"
                      action="{{ url_for('network.archive_pull_latest', inst_id=inst.id, remote_job_id=row.job_id) }}"
                      onsubmit="return confirm('Rapatrier la dernière archive de « {{ row.job_name }} » ?')">
                  <button type="submit" class="btn-ghost btn-sm">← Rapatrier</button>
                </form>
                {% endif %}
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}
  </div>
  {% endfor %}
</div>
{% endif %}

{% endblock %}

{% block scripts %}
<script>
(function() {
  const selectAll = document.getElementById('select-all');
  const checkboxes = () => [...document.querySelectorAll('.job-checkbox')];
  const bulkBar = document.getElementById('bulk-bar');
  const bulkCount = document.getElementById('bulk-count');

  function updateBar() {
    const checked = checkboxes().filter(c => c.checked);
    bulkCount.textContent = checked.length;
    if (checked.length > 0) bulkBar.classList.remove('hidden');
    else bulkBar.classList.add('hidden');
  }

  if (selectAll) {
    selectAll.addEventListener('change', function() {
      checkboxes().forEach(c => c.checked = this.checked);
      updateBar();
    });
  }

  document.addEventListener('change', function(e) {
    if (!e.target.classList.contains('job-checkbox')) return;
    const all = checkboxes();
    if (selectAll) {
      selectAll.checked = all.every(c => c.checked);
      selectAll.indeterminate = all.some(c => c.checked) && !all.every(c => c.checked);
    }
    updateBar();
  });

  window.bulkAction = function(action, confirmMsg) {
    const checked = checkboxes().filter(c => c.checked);
    if (!checked.length) return;
    if (confirmMsg && !confirm(confirmMsg)) return;
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '{{ url_for("jobs.jobs_bulk") }}';
    const ai = document.createElement('input');
    ai.type = 'hidden'; ai.name = 'action'; ai.value = action;
    form.appendChild(ai);
    checked.forEach(c => {
      const inp = document.createElement('input');
      inp.type = 'hidden'; inp.name = 'job_ids'; inp.value = c.value;
      form.appendChild(inp);
    });
    document.body.appendChild(form);
    form.submit();
  };
})();
</script>
{% endblock %}
