{% extends 'base.html' %}

{% block content %}
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  <div class="bg-white shadow-md rounded-lg overflow-hidden">

    <!-- Page header -->
    <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
      <h1 class="text-2xl font-bold text-gray-900 flex items-center">
        <i class="fas fa-shield-alt mr-3 text-red-500"></i>
        {{ form_title }}
      </h1>
      <a href="{% url 'netscan-dashboard' %}" class="text-sm text-gray-500 hover:text-gray-700">
        <i class="fas fa-arrow-left mr-1"></i> Back
      </a>
    </div>

    <form method="post" id="profile-form" class="px-4 py-5 sm:p-6 space-y-8">
      {% csrf_token %}

      <!-- General -->
      <div>
        <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4">General</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

          <!-- Name (full width) -->
          <div class="sm:col-span-2">
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_name">Name</label>
            {{ form.name }}
            {% for error in form.name.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <!-- Enabled -->
          <div class="flex items-center gap-2">
            {{ form.enabled }}
            <label class="text-sm font-medium text-gray-700" for="id_enabled">Enabled</label>
          </div>

          <!-- Schedule interval -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_schedule_interval">Scan interval</label>
            {{ form.schedule_interval }}
            {% for error in form.schedule_interval.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

        </div>
      </div>

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

      <!-- Network -->
      <div>
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wide">Network</h2>
          <button type="button" id="auto-detect-btn"
                  class="inline-flex items-center px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 text-sm font-medium border border-blue-200">
            <i class="fas fa-magic mr-2"></i>
            Auto-detect
          </button>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_gateway_ip">Gateway IP</label>
            {{ form.gateway_ip }}
            {% for error in form.gateway_ip.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_public_ip">Public IP</label>
            {{ form.public_ip }}
            {% for error in form.public_ip.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_network_cidr">Network CIDR</label>
            {{ form.network_cidr }}
            {% if form.network_cidr.help_text %}<p class="text-xs text-gray-400 mt-1">{{ form.network_cidr.help_text }}</p>{% endif %}
            {% for error in form.network_cidr.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_auth_provider_host">Auth provider host</label>
            {{ form.auth_provider_host }}
            {% if form.auth_provider_host.help_text %}<p class="text-xs text-gray-400 mt-1">{{ form.auth_provider_host.help_text }}</p>{% endif %}
            {% for error in form.auth_provider_host.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_domains_text">Domains</label>
            {{ form.domains_text }}
            {% if form.domains_text.help_text %}<p class="text-xs text-gray-400 mt-1">{{ form.domains_text.help_text }}</p>{% endif %}
            {% for error in form.domains_text.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_cameras_text">Camera IPs</label>
            {{ form.cameras_text }}
            {% if form.cameras_text.help_text %}<p class="text-xs text-gray-400 mt-1">{{ form.cameras_text.help_text }}</p>{% endif %}
            {% for error in form.cameras_text.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

        </div>
      </div>

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

      <!-- Telegram Notifications -->
      <div>
        <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4">Telegram Notifications</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_telegram_bot_token">Bot token</label>
            {{ form.telegram_bot_token }}
            {% for error in form.telegram_bot_token.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_telegram_chat_id">Chat ID</label>
            {{ form.telegram_chat_id }}
            {% for error in form.telegram_chat_id.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="id_notify_on_severity">Notify on severity</label>
            {{ form.notify_on_severity }}
            {% for error in form.notify_on_severity.errors %}<p class="text-xs text-red-600 mt-1">{{ error }}</p>{% endfor %}
          </div>

        </div>

        {% if object.pk %}
        <div class="mt-4">
          <button type="button" id="test-telegram-btn"
                  class="inline-flex items-center px-4 py-2 bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 text-sm font-medium border border-blue-200">
            <i class="fas fa-paper-plane mr-2"></i>
            Test Telegram
          </button>
          <span id="test-telegram-result" class="ml-3 text-sm hidden"></span>
        </div>
        {% endif %}
      </div>

      <!-- Actions -->
      <div class="flex justify-end gap-3 pt-2 border-t border-gray-100">
        <a href="{% url 'netscan-dashboard' %}"
           class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-gray-700 bg-gray-200 hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
          Cancel
        </a>
        <button type="submit"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
          Save Profile
        </button>
      </div>

    </form>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.getElementById('auto-detect-btn').addEventListener('click', function () {
  const btn = this;
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Detecting...';

  fetch("{% url 'netscan-detect-network' %}")
    .then(r => r.json())
    .then(data => {
      if (data.gateway_ip)   document.getElementById('id_gateway_ip').value   = data.gateway_ip;
      if (data.public_ip)    document.getElementById('id_public_ip').value    = data.public_ip;
      if (data.network_cidr) document.getElementById('id_network_cidr').value = data.network_cidr;

      btn.innerHTML = '<i class="fas fa-check mr-2"></i>Detected!';
      btn.classList.replace('text-blue-700', 'text-green-700');
      btn.classList.replace('bg-blue-50',    'bg-green-50');
      btn.classList.replace('border-blue-200', 'border-green-200');
      setTimeout(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-magic mr-2"></i>Auto-detect';
        btn.classList.replace('text-green-700', 'text-blue-700');
        btn.classList.replace('bg-green-50',    'bg-blue-50');
        btn.classList.replace('border-green-200', 'border-blue-200');
      }, 3000);
    })
    .catch(() => {
      btn.innerHTML = '<i class="fas fa-exclamation-triangle mr-2"></i>Failed';
      setTimeout(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-magic mr-2"></i>Auto-detect';
      }, 3000);
    });
});
</script>

{% if object.pk %}
<script>
document.getElementById('test-telegram-btn').addEventListener('click', function () {
  const btn = this;
  const result = document.getElementById('test-telegram-result');
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Sending...';
  result.className = 'ml-3 text-sm hidden';

  fetch("{% url 'netscan-test-telegram' object.pk %}", {
    method: 'POST',
    headers: {'X-CSRFToken': '{{ csrf_token }}'},
  })
  .then(r => r.json())
  .then(data => {
    result.classList.remove('hidden');
    if (data.ok) {
      result.className = 'ml-3 text-sm text-green-600';
      result.textContent = '✓ Test message sent!';
    } else {
      result.className = 'ml-3 text-sm text-red-600';
      result.textContent = '✗ ' + (data.error || 'Failed');
    }
  })
  .catch(() => {
    result.classList.remove('hidden');
    result.className = 'ml-3 text-sm text-red-600';
    result.textContent = '✗ Network error';
  })
  .finally(() => {
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>Test Telegram';
  });
});
</script>
{% endif %}
{% endblock %}
