{% extends 'admin_frontend/base.html' %}
{% load breadcrumbs %}
{% block title %}Provided Services{% endblock %}
{% block content %}
{% render_breadcrumbs breadcrumbs %}
<div class="flex items-center justify-between mb-4">
  <h1 class="text-xl font-semibold">Provided Services</h1>
  <a href="{% url 'recycle_core:service_create' %}" class="btn-outline">New Service</a>
  <style>.btn-outline{border:1px solid #cbd5e1;padding:.375rem .5rem;border-radius:.375rem}</style>
</div>

<!-- SortableJS CDN -->

<div class="bg-white rounded shadow overflow-hidden"
     x-data="servicesSorter()">
  <div class="px-4 py-2 text-xs text-gray-500 border-b flex items-center gap-3">
    <span>Drag the handle to reorder. Changes save automatically.</span>
    <template x-if="saving">
      <span class="text-blue-600">Saving…</span>
    </template>
    <template x-if="saved">
      <span class="text-green-600">Saved.</span>
    </template>
    <template x-if="error">
      <span class="text-red-600" x-text="error"></span>
    </template>
  </div>
  <table class="min-w-full text-sm">
    <thead class="bg-gray-50 text-left">
      <tr>
        <th class="px-4 py-2 w-16">Order</th>
        <th class="px-4 py-2">Title</th>
        <th class="px-4 py-2">Description</th>
        <th class="px-4 py-2 w-24">Status</th>
        <th class="px-4 py-2 w-48">Actions</th>
      </tr>
    </thead>
    <tbody x-ref="tbody">
      {% for s in services %}
      <tr class="border-t" :data-id="{{ s.id }}" data-id="{{ s.id }}">
        <td class="px-4 py-2 text-gray-600">
          <div class="flex items-center gap-2">
            <span class="drag-handle cursor-grab select-none" title="Drag to reorder">⋮⋮</span>
            <span class="order-index">{{ s.display_order|add:1 }}</span>
          </div>
        </td>
        <td class="px-4 py-2 font-medium">{{ s.title }}</td>
        <td class="px-4 py-2 text-gray-700">{{ s.description|truncatechars:140 }}</td>
        <td class="px-4 py-2">
          {% if s.is_enabled %}
            <span class="inline-flex items-center rounded bg-green-50 text-green-700 px-2 py-0.5 text-xs">Enabled</span>
          {% else %}
            <span class="inline-flex items-center rounded bg-gray-100 text-gray-600 px-2 py-0.5 text-xs">Disabled</span>
          {% endif %}
        </td>
        <td class="px-4 py-2">
          <div class="flex items-center gap-3">
            <a href="{% url 'recycle_core:service_edit' s.pk %}" class="text-blue-600 hover:text-blue-700">Edit</a>
            <form method="post" action="{% url 'recycle_core:service_toggle_enabled' s.pk %}">
              {% csrf_token %}
              <button type="submit" class="text-gray-700 hover:text-gray-900">{% if s.is_enabled %}Disable{% else %}Enable{% endif %}</button>
            </form>
            <form method="post" action="{% url 'recycle_core:service_delete' s.pk %}" onsubmit="return confirm('Delete this service?');">
              {% csrf_token %}
              <button type="submit" class="text-red-600 hover:text-red-700">Delete</button>
            </form>
          </div>
        </td>
      </tr>
      {% empty %}
      <tr>
        <td colspan="4" class="px-4 py-6 text-center text-gray-500">No services yet. Click New Service to add one.</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
  <div class="px-4 py-3 text-xs text-gray-500 border-t">Sorted by display order ascending.</div>
  <style>
    .btn{background:#1d4ed8;color:#fff;padding:.5rem .75rem;border-radius:.375rem}
    .drag-handle{font-weight:700;line-height:1}
  </style>
</div>

<script>
  function servicesSorter(){
    return {
      saving: false,
      saved: false,
      error: '',
      init(){
        // Wait for SortableJS to be present
        const initSortable = () => {
          if (!window.Sortable) { setTimeout(initSortable, 50); return; }
          const el = this.$refs.tbody;
          new Sortable(el, {
            handle: '.drag-handle',
            animation: 150,
            ghostClass: 'bg-yellow-50',
            onEnd: () => this.persistOrder()
          });
        };
        initSortable();
      },
      persistOrder(){
        this.saving = true; this.saved = false; this.error='';
        const ids = Array.from(this.$refs.tbody.children).map(tr => parseInt(tr.dataset.id));
        // Update visible order indices immediately (1-based display)
        Array.from(this.$refs.tbody.children).forEach((tr, idx) => {
          const el = tr.querySelector('.order-index');
          if (el) el.textContent = idx + 1;
        });
        fetch("{% url 'recycle_core:services_reorder' %}", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken'),
          },
          body: JSON.stringify({ ids })
        }).then(r => {
          if(!r.ok) throw new Error('Save failed');
          return r.json();
        }).then(() => {
          this.saved = true;
        }).catch(err => {
          this.error = err.message || 'Error saving order';
        }).finally(() => {
          this.saving = false;
          setTimeout(() => { this.saved = false }, 1500);
        });
      }
    }
  }
  function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
  }
</script>
{% endblock %}
