{% extends "base.html" %}
{% block title %}Paramètres{% endblock %}

{% block content %}
<div class="flex items-center justify-between mb-6">
  <h1 class="text-xl font-bold text-gray-900">Paramètres</h1>
  <div class="flex gap-2">
    <a href="{{ url_for('dest.destination_new') }}" id="btn-new-dest" class="btn-primary btn-sm hidden">
      + Nouvelle destination
    </a>
    <a href="{{ url_for('network.remote_instance_new') }}" id="btn-new-inst" class="btn-primary btn-sm hidden">
      + Ajouter une instance
    </a>
  </div>
</div>

{# ── Onglets ─────────────────────────────────────────────────────── #}
<div class="flex border-b border-gray-200 mb-6 gap-1">
  <button id="tab-btn-destinations" onclick="setTab('destinations')"
          class="tab-btn px-4 py-2 text-sm font-medium border-b-2 border-blue-600 text-blue-600 -mb-px">
    Destinations
  </button>
  <button id="tab-btn-instances" onclick="setTab('instances')"
          class="tab-btn px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 -mb-px">
    Instances
  </button>
  <button id="tab-btn-config" onclick="setTab('config')"
          class="tab-btn px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 -mb-px">
    Configuration
  </button>
</div>

{# ══════════════════ PANNEAU : DESTINATIONS ═══════════════════════ #}
<div id="pane-destinations">

{% if not destinations %}
  <div class="bg-white rounded-xl border border-gray-200 px-6 py-12 text-center text-gray-400">
    <p class="text-lg">Aucune destination configurée.</p>
    <p class="text-sm mt-2">Les archives sont conservées localement uniquement.</p>
    <a href="{{ url_for('dest.destination_new') }}" class="mt-4 inline-block text-blue-600 hover:underline text-sm">
      Configurer une première destination →
    </a>
  </div>
{% else %}
  <div class="space-y-4">
    {% for dest in destinations %}
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
      <div class="flex items-start justify-between gap-4">
        <div class="space-y-1 min-w-0">
          <div class="flex items-center gap-2">
            <span class="font-semibold text-gray-900">{{ dest.name }}</span>
            {% if dest.enabled %}
              <span class="bg-green-100 text-green-700 text-xs px-2 py-0.5 rounded-full font-medium">actif</span>
            {% else %}
              <span class="bg-gray-100 text-gray-500 text-xs px-2 py-0.5 rounded-full font-medium">inactif</span>
            {% endif %}
          </div>
          <p class="text-sm font-mono text-gray-600">
            {{ dest.user }}@{{ dest.host }}:{{ dest.port }} → {{ dest.remote_path }}
          </p>
          {% if dest.jobs %}
            <p class="text-xs text-gray-400">
              Utilisée par : {{ dest.jobs | map(attribute='name') | join(', ') }}
            </p>
          {% endif %}
        </div>

        <div class="flex items-center gap-2 shrink-0">
          <form method="post" action="{{ url_for('dest.destination_test', dest_id=dest.id) }}">
            <button type="submit" class="btn-secondary btn-sm">Tester</button>
          </form>
          <a href="{{ url_for('dest.destination_edit', dest_id=dest.id) }}"
             class="btn-secondary btn-sm">Éditer</a>
          <form method="post" action="{{ url_for('dest.destination_delete', dest_id=dest.id) }}"
                onsubmit="return confirm('Supprimer la destination « {{ dest.name }} » ?')">
            <button type="submit" class="btn-danger btn-icon-sm">✕</button>
          </form>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
{% endif %}

</div>{# /pane-destinations #}

{# ══════════════════ PANNEAU : INSTANCES ══════════════════════════ #}
<div id="pane-instances" class="hidden">

{% if not instances %}
  <div class="bg-white rounded-xl border border-gray-200 px-6 py-12 text-center text-gray-400">
    <p class="text-lg">Aucune instance distante configurée.</p>
    <p class="text-sm mt-2">Ajoutez une instance pour voir son état et déclencher des sauvegardes à distance.</p>
    <a href="{{ url_for('network.remote_instance_new') }}" class="mt-4 inline-block text-blue-600 hover:underline text-sm">
      Ajouter une première instance →
    </a>
  </div>
{% else %}
  <div class="space-y-4">
    {% for inst in instances %}
    {% set status_color = {
      'online':  'bg-green-100 text-green-700',
      'error':   'bg-red-100 text-red-700',
      'offline': 'bg-gray-100 text-gray-500',
    }.get(inst.status, 'bg-gray-100 text-gray-400') %}

    <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
      <div class="flex items-start justify-between gap-4">
        <div class="space-y-1 min-w-0 flex-1">
          <div class="flex items-center gap-2 flex-wrap">
            <span class="font-semibold text-gray-900">{{ inst.name }}</span>
            <span class="text-xs px-2 py-0.5 rounded-full font-medium {{ status_color }}">
              {{ inst.status or 'unknown' }}
            </span>
            {% if inst.last_seen %}
              <span class="text-xs text-gray-400">vu {{ inst.last_seen.strftime('%d/%m %H:%M') }}</span>
            {% endif %}
          </div>
          <p class="text-sm font-mono text-gray-500">{{ inst.url_display }}</p>
          {% if inst.remote_runs %}
            <p class="text-xs text-gray-400">
              {{ inst.remote_runs | length }} job{{ 's' if inst.remote_runs | length != 1 }} synchronisé{{ 's' if inst.remote_runs | length != 1 }}
            </p>
          {% endif %}
        </div>
        <div class="flex items-center gap-2 shrink-0">
          <form method="post" action="{{ url_for('network.remote_instance_test', inst_id=inst.id) }}">
            <button type="submit" class="btn-secondary btn-sm">Tester</button>
          </form>
          <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>
          <a href="{{ url_for('network.remote_instance_edit', inst_id=inst.id) }}"
             class="btn-secondary btn-sm">Éditer</a>
          <form method="post" action="{{ url_for('network.remote_instance_delete', inst_id=inst.id) }}"
                onsubmit="return confirm('Supprimer l\'instance « {{ inst.name }} » ?')">
            <button type="submit" class="btn-danger btn-icon-sm">✕</button>
          </form>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
{% endif %}

</div>{# /pane-instances #}

{# ══════════════════ PANNEAU : CONFIGURATION ══════════════════════ #}
<div id="pane-config" class="hidden max-w-xl">

  <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-3 mb-6">
    <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">API — Token d'accès</h2>
    <p class="text-xs text-gray-500">
      Communiquez ce token aux autres instances BackupManager pour qu'elles puissent se connecter à celle-ci.
    </p>
    <div class="flex items-center gap-2">
      <input type="text" id="api-token" readonly value="{{ api_token }}"
             class="flex-1 border border-gray-200 bg-gray-50 rounded-lg px-3 py-2 text-sm font-mono text-gray-700 focus:outline-none select-all">
      <button type="button" onclick="copyToken()"
              class="btn-secondary btn-sm shrink-0">Copier</button>
    </div>
    {% if instance_url %}
    <p class="text-xs text-gray-400">
      URL de cette instance : <span class="font-mono">{{ instance_url }}</span>
    </p>
    {% endif %}
  </div>

  <form method="post" class="space-y-6">

    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Serveur SMTP</h2>

      <div class="grid grid-cols-3 gap-3">
        <div class="col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-1">Hôte SMTP</label>
          <input type="text" name="smtp_host" value="{{ cfg.smtp_host }}"
                 placeholder="smtp.exemple.fr"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Port</label>
          <input type="number" name="smtp_port" min="1" max="65535"
                 value="{{ cfg.smtp_port or 587 }}"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Utilisateur</label>
          <input type="text" name="smtp_user" value="{{ cfg.smtp_user }}"
                 placeholder="user@exemple.fr"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Mot de passe</label>
          <input type="password" name="smtp_password" value="{{ cfg.smtp_password }}"
                 placeholder="••••••••"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Expéditeur (From)</label>
          <input type="email" name="smtp_from" value="{{ cfg.smtp_from }}"
                 placeholder="backup@exemple.fr"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
          <p class="text-xs text-gray-400 mt-1">Si vide, utilise l'utilisateur SMTP.</p>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Destinataire (To)</label>
          <input type="email" name="smtp_to" value="{{ cfg.smtp_to }}"
                 placeholder="admin@exemple.fr"
                 class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>

      <div class="flex items-center gap-6">
        <label class="flex items-center gap-2">
          <input type="checkbox" name="smtp_tls" value="1"
                 {% if cfg.smtp_tls == '1' %}checked{% endif %}
                 class="rounded border-gray-300 text-blue-600">
          <span class="text-sm font-medium text-gray-700">STARTTLS</span>
        </label>
        <label class="flex items-center gap-2">
          <input type="checkbox" name="smtp_ssl" value="1"
                 {% if cfg.smtp_ssl == '1' %}checked{% endif %}
                 class="rounded border-gray-300 text-blue-600">
          <span class="text-sm font-medium text-gray-700">SSL/TLS direct (port 465)</span>
        </label>
      </div>
    </div>

    <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-3">
      <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Notifications</h2>

      <label class="flex items-center gap-2">
        <input type="checkbox" name="notify_on_error" value="1"
               {% if cfg.notify_on_error != '0' %}checked{% endif %}
               class="rounded border-gray-300 text-blue-600">
        <span class="text-sm font-medium text-gray-700">Notifier en cas d'erreur</span>
      </label>

      <label class="flex items-center gap-2">
        <input type="checkbox" name="notify_on_success" value="1"
               {% if cfg.notify_on_success == '1' %}checked{% endif %}
               class="rounded border-gray-300 text-blue-600">
        <span class="text-sm font-medium text-gray-700">Notifier en cas de succès</span>
      </label>
    </div>

    <div class="flex gap-3 flex-wrap">
      <button type="submit" name="action" value="save" class="btn-primary btn-md">
        Enregistrer
      </button>
      <button type="submit" name="action" value="test_smtp" class="btn-secondary btn-md">
        Envoyer un email de test
      </button>
    </div>

  </form>

  {# ── Export / Import ── #}
  <div class="bg-white rounded-xl border border-gray-200 p-6 space-y-5 mt-6">
    <h2 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Export / Import de configuration</h2>

    <div>
      <p class="text-sm text-gray-600 mb-3">
        Exporte tous les jobs, destinations, instances distantes et paramètres SMTP dans un fichier JSON.
      </p>
      <p class="text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-3">
        Les fichiers de clés SSH ne sont <strong>pas inclus</strong> dans l'export — ils devront être restaurés manuellement dans <code class="font-mono">data_dir/keys/</code>.
      </p>
      <a href="{{ url_for('cfg.export_config') }}"
         class="btn-secondary btn-md inline-block">
        Télécharger la configuration
      </a>
    </div>

    <hr class="border-gray-100">

    <div>
      <p class="text-sm text-gray-600 mb-3">
        Importe un fichier exporté par BackupManager. Les jobs et destinations existants portant le même nom seront mis à jour.
      </p>
      <form method="post" enctype="multipart/form-data"
            action="{{ url_for('cfg.import_config') }}"
            class="flex items-center gap-3 flex-wrap">
        <input type="file" name="config_file" accept=".json"
               required
               class="text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border file:border-gray-300 file:bg-white file:text-sm file:font-medium file:text-gray-700 hover:file:bg-gray-50">
        <button type="submit" class="btn-primary btn-md"
                onclick="return confirm('Importer cette configuration ? Les jobs et destinations portant le même nom seront mis à jour.')">
          Importer
        </button>
      </form>
    </div>
  </div>

</div>{# /pane-config #}

<script>
const TAB_NAMES = ['destinations', 'instances', 'config'];

function setTab(name) {
  TAB_NAMES.forEach(function(t) {
    const pane = document.getElementById('pane-' + t);
    const btn  = document.getElementById('tab-btn-' + t);
    const active = t === name;
    pane.classList.toggle('hidden', !active);
    btn.classList.toggle('border-blue-600', active);
    btn.classList.toggle('text-blue-600', active);
    btn.classList.toggle('border-transparent', !active);
    btn.classList.toggle('text-gray-500', !active);
  });
  document.getElementById('btn-new-dest').classList.toggle('hidden', name !== 'destinations');
  document.getElementById('btn-new-inst').classList.toggle('hidden', name !== 'instances');
  history.replaceState(null, '', location.pathname + '?tab=' + name);
}

function copyToken() {
  const input = document.getElementById('api-token');
  navigator.clipboard.writeText(input.value).then(() => {
    const btn = event.target;
    btn.textContent = 'Copié !';
    setTimeout(() => btn.textContent = 'Copier', 2000);
  });
}

// Restore tab from URL
const urlTab = new URLSearchParams(location.search).get('tab');
if (TAB_NAMES.includes(urlTab)) {
  setTab(urlTab);
} else {
  setTab('destinations');
}
</script>
{% endblock %}
