{% extends "admin_frontend/base.html" %}
{% load breadcrumbs widget_tweaks humanize %}
{% block title %}Weigh Ticket {{ ticket.ticket_number|default:ticket.id }}{% endblock %}
{% block content %}
{% render_breadcrumbs breadcrumbs %}
<div class="flex items-center justify-between mb-4">
  <h1 class="text-2xl font-semibold">Weigh Ticket {{ ticket.ticket_number|default:ticket.id }}</h1>
  <div class="flex items-center gap-2">
    <a href="{% url 'recycle_core:pickup_detail' ticket.pickup.id %}" class="btn-outline">View Pickup</a>
    {% if perms.recycle_core.generate_invoice %}
    <form method="post" action="{{ generate_url }}">
      {% csrf_token %}
      <button class="px-3 py-2 rounded bg-blue-600 text-white">Generate Invoice</button>
    </form>
    {% endif %}
    <form method="post" action="{% url 'recycle_core:weigh_ticket_recalc_carbon' ticket.id %}">
      {% csrf_token %}
      <button class="px-3 py-2 rounded bg-gray-700 text-white">Recalculate Carbon</button>
    </form>
  </div>
</div>

<div class="grid grid-cols-1 md:grid-cols-10 gap-6 mb-6">
  <div class="bg-white rounded shadow p-4 md:col-span-3">
    <h2 class="font-medium mb-2">Details</h2>
    <dl class="grid grid-cols-3 gap-2 text-sm">
      <dt class="text-gray-500">Pickup</dt><dd class="col-span-2"><a class="text-blue-700 hover:underline" href="{% url 'recycle_core:pickup_detail' ticket.pickup.id %}">#{{ ticket.pickup.id }}</a></dd>
      <dt class="text-gray-500">Customer</dt><dd class="col-span-2">{{ ticket.pickup.customer.name }}</dd>
      <dt class="text-gray-500">Recorded</dt><dd class="col-span-2">{{ ticket.recorded_at }}</dd>
      <dt class="text-gray-500">Gross</dt><dd class="col-span-2 text-right">{{ ticket.gross_weight|floatformat:3|intcomma }} {{ ticket.unit }}</dd>
      <dt class="text-gray-500">Tare</dt><dd class="col-span-2 text-right">{{ ticket.tare_weight|floatformat:3|intcomma }} {{ ticket.unit }}</dd>
      <dt class="text-gray-500">Net</dt><dd class="col-span-2 text-right">{{ ticket.net_weight|floatformat:3|intcomma }} {{ ticket.unit }}</dd>
      <dt class="text-gray-500">Finalized</dt><dd class="col-span-2">{% if is_finalized %}Yes{% else %}No{% endif %}</dd>
    </dl>
    {% if not is_finalized %}
    <div class="mt-4 space-y-2">
      {% if allow_adjust_net %}
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="adjust_net_to_lines">
        <button class="px-3 py-2 rounded bg-gray-800 text-white w-full">Adjust Net to Lines</button>
      </form>
      {% endif %}
      {% if allow_residual %}
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="add_residual_line">
        <button class="px-3 py-2 rounded bg-gray-700 text-white w-full">Add Residual Line</button>
      </form>
      {% endif %}
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="finalize_ticket">
        <button class="px-3 py-2 rounded bg-blue-600 text-white w-full">Finalize Ticket</button>
      </form>
    </div>
    {% endif %}
    {% if perms.recycle_core.edit_weigh_ticket and not is_finalized %}
      <div class="mt-6 border-t pt-4">
        <button type="button" class="px-3 py-2 rounded bg-emerald-600 text-white w-full" onclick="document.getElementById('edit-weights-modal').classList.remove('hidden')">Edit Weights</button>
      </div>
      <!-- Modal -->
      <div id="edit-weights-modal" class="hidden fixed inset-0 z-50">
        <div class="absolute inset-0 bg-black/50" onclick="document.getElementById('edit-weights-modal').classList.add('hidden')"></div>
        <div class="relative max-w-md w-full mx-auto mt-20 bg-white rounded shadow p-4">
          <div class="flex items-center justify-between mb-2">
            <h3 class="font-medium">Edit Weights</h3>
            <button type="button" class="text-gray-600 hover:text-gray-800" onclick="document.getElementById('edit-weights-modal').classList.add('hidden')">✕</button>
          </div>
          <form method="post" class="grid grid-cols-1 gap-3">
            {% csrf_token %}
            <input type="hidden" name="action" value="edit_weights">
            {% if weights_form.non_field_errors %}
              <div class="text-red-700 text-sm">{{ weights_form.non_field_errors }}</div>
            {% endif %}
            <div>
              <label class="block text-sm text-gray-600 mb-1">Gross</label>
              {{ weights_form.gross_weight|attr:"class:w-full max-w-full text-right" }}
              {% if weights_form.gross_weight.errors %}
                <div class="text-red-700 text-xs mt-1">{{ weights_form.gross_weight.errors|striptags }}</div>
              {% endif %}
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">Tare</label>
              {{ weights_form.tare_weight|attr:"class:w-full max-w-full text-right" }}
              {% if weights_form.tare_weight.errors %}
                <div class="text-red-700 text-xs mt-1">{{ weights_form.tare_weight.errors|striptags }}</div>
              {% endif %}
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">Unit</label>
              {% if lines %}
                <div title="Cannot change unit while lines exist">
                  {{ weights_form.unit|attr:"class:w-full max-w-full"|attr:"disabled:disabled" }}
                  <input type="hidden" name="unit" value="{{ weights_form.unit.value|default:ticket.unit }}" />
                </div>
              {% else %}
                  {{ weights_form.unit|attr:"class:w-full max-w-full" }}
              {% endif %}
              {% if weights_form.unit.errors %}
                <div class="text-red-700 text-xs mt-1">{{ weights_form.unit.errors|striptags }}</div>
              {% endif %}
            </div>
            <div class="flex items-center justify-end gap-2 pt-1">
              <button type="button" class="px-3 py-2 rounded border border-gray-300 text-gray-700" onclick="document.getElementById('edit-weights-modal').classList.add('hidden')">Cancel</button>
              <button class="px-3 py-2 rounded bg-emerald-600 text-white">Save</button>
            </div>
          </form>
        </div>
      </div>
    {% endif %}
  </div>
  <div class="bg-white rounded shadow p-4 md:col-span-7">
    <h2 class="font-medium mb-2">Lines</h2>
    <div class="text-sm mb-3">
      <div>
        <span class="text-gray-600">Net Weight:</span>
        <span class="font-medium">{{ ticket.net_weight }} {{ ticket.unit }}</span>
      </div>
      <div>
        <span class="text-gray-600">Sum of Lines ({{ ticket.unit }}):</span>
        <span class="font-medium">{{ lines_sum }} {{ ticket.unit }}</span>
        {% if has_unconvertible %}
          <span class="ml-2 text-xs text-amber-700">Includes unconverted items (different units)</span>
        {% endif %}
      </div>
      <div>
        <span class="text-gray-600">Difference:</span>
        <span class="font-medium {% if lines_delta != 0 %}text-red-700{% endif %}">{{ lines_delta }} {{ ticket.unit }}</span>
      </div>
    </div>
    <table class="min-w-full">
      <thead>
        <tr class="text-left text-sm text-gray-600">
          <th class="px-2 py-1">Material</th>
          <th class="px-2 py-1 text-right">Qty</th>
          <th class="px-2 py-1">Unit</th>
          <th class="px-2 py-1">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y">
        {% for line in lines %}
          <tr>
            <form method="post">
              {% csrf_token %}
              <input type="hidden" name="action" value="edit">
              <input type="hidden" name="line_id" value="{{ line.id }}">
              <td class="px-2 py-1">{{ line.form.material|attr:"class:w-full max-w-full" }}</td>
              <td class="px-2 py-1 text-right">{{ line.form.quantity|attr:"class:w-full max-w-full text-right" }}</td>
              <td class="px-2 py-1">{{ line.form.unit|attr:"class:w-full max-w-full" }}</td>
              <td class="px-2 py-1">
                <button class="px-2 py-1 rounded bg-blue-600 text-white text-sm">Save</button>
                <button form="del-line-{{ line.id }}" class="px-2 py-1 rounded bg-red-600 text-white text-sm" onclick="return confirm('Delete this line?')">Delete</button>
              </td>
            </form>
            <form id="del-line-{{ line.id }}" method="post" class="hidden">
              {% csrf_token %}
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="line_id" value="{{ line.id }}">
            </form>
          </tr>
        {% empty %}
          <tr>
            <td colspan="3" class="px-2 py-2 text-gray-500">No lines.</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
    <div class="mt-4 border-t pt-4">
      <h3 class="font-medium mb-2">Add Line</h3>
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="add">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 md:gap-6 items-end">
          <div>
            <label class="block text-sm text-gray-600 mb-1">Material</label>
            {{ add_line_form.material|attr:"class:w-full max-w-full" }}
          </div>
          <div>
            <label class="block text-sm text-gray-600 mb-1">Quantity</label>
            {{ add_line_form.quantity|attr:"class:w-full max-w-full text-right" }}
          </div>
          <div>
            <label class="block text-sm text-gray-600 mb-1">Unit</label>
            {{ add_line_form.unit|attr:"class:w-full max-w-full" }}
          </div>
          <div>
            <button class="px-3 py-2 rounded bg-blue-600 text-white">Add</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="bg-white rounded shadow p-4">
  <h2 class="font-medium mb-2">Documents</h2>
  <div class="mb-3">
    <form method="post" action="{% url 'recycle_core:documents_list' %}" enctype="multipart/form-data" class="flex flex-wrap items-center gap-2">
      {% csrf_token %}
      <input type="hidden" name="organization" value="{{ ticket.pickup.organization.id }}" />
      <input type="hidden" name="content_type" value="{{ ct_id }}" />
      <input type="hidden" name="object_id" value="{{ ticket.id }}" />
      <input type="text" name="kind" placeholder="Kind (optional)" class="border rounded px-3 py-2" />
      <input type="file" name="file" class="border rounded px-3 py-2" required />
      <button class="px-3 py-2 rounded bg-blue-600 text-white">Upload</button>
    </form>
  </div>
  <table class="min-w-full">
    <thead>
      <tr class="text-left text-sm text-gray-600">
        <th class="px-2 py-1">Kind</th>
        <th class="px-2 py-1">File</th>
        <th class="px-2 py-1">Uploaded</th>
      </tr>
    </thead>
    <tbody class="divide-y">
      {% for d in documents %}
      <tr>
        <td class="px-2 py-1">{{ d.kind|default:"-" }}</td>
        <td class="px-2 py-1"><a href="{{ d.file.url }}" target="_blank" class="text-blue-700 hover:underline">Download</a></td>
        <td class="px-2 py-1">{{ d.created_at }}</td>
      </tr>
      {% empty %}
      <tr>
        <td colspan="3" class="px-2 py-2 text-gray-500">No documents yet.</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
{% endblock %}
