{% extends "admin_frontend/base.html" %}
{% load crispy_forms_tags breadcrumbs %}
{% block title %}Edit Material{% endblock %}
{% block content %}
{% render_breadcrumbs breadcrumbs %}
<div class="bg-white rounded shadow p-4">
  <h1 class="text-xl font-semibold mb-4">Edit Material</h1>

  {% if item %}
  {% with imgs=item.images.all %}
  {% if imgs %}
  <div class="mb-4"
       x-data="imagesSorter()">
    <h2 class="text-lg font-medium mb-2">Existing Images</h2>
    <div class="text-xs text-gray-500 mb-2 flex items-center gap-3">
      <span>Drag the handle to reorder. Saves 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>
    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3" x-ref="grid">
      {% for im in imgs %}
        <div class="border rounded p-2 bg-white flex flex-col items-center gap-2" data-id="{{ im.id }}">
          <div class="w-full flex items-center justify-between text-xs text-gray-500">
            <span class="drag-handle cursor-grab" title="Drag to reorder">⋮⋮</span>
            <span class="order-index">{{ im.display_order|add:1 }}</span>
          </div>
          <img src="{{ im.image.url }}" alt="{{ im.caption|default:'Material image' }}" class="w-28 h-28 object-cover rounded" />
          {% if im.caption %}
            <div class="text-xs text-gray-600 text-center">{{ im.caption }}</div>
          {% endif %}
        </div>
      {% endfor %}
    </div>
    <style>.drag-handle{font-weight:700;line-height:1}</style>
  </div>
  <script>
    function imagesSorter(){
      return {
        saving: false,
        saved: false,
        error: '',
        init(){
          const wait = () => {
            if (!window.Sortable) { setTimeout(wait, 50); return; }
            new Sortable(this.$refs.grid, {
              handle: '.drag-handle',
              animation: 150,
              ghostClass: 'bg-yellow-50',
              onEnd: () => this.persistOrder(),
            });
          };
          wait();
        },
        persistOrder(){
          this.saving = true; this.saved = false; this.error = '';
          const ids = Array.from(this.$refs.grid.children).map(el => parseInt(el.dataset.id));
          // Update visible order indices (1-based)
          Array.from(this.$refs.grid.children).forEach((el, idx) => {
            const label = el.querySelector('.order-index');
            if (label) label.textContent = idx + 1;
          });
          fetch("{% url 'recycle_core:material_images_reorder' item.pk %}", {
            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>
  {% endif %}
  {% endwith %}
  {% endif %}

  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="mt-3 flex gap-2">
      <a href="{{ cancel_url }}" class="px-3 py-2 rounded border">Cancel</a>
      <button class="px-3 py-2 rounded bg-blue-600 text-white">Save</button>
    </div>
  </form>
</div>
{% endblock %}
