{% extends "markettracker/base.html" %}
{% load i18n humanize %}
{% block page_title %}{% trans "Manage Stock" %}{% endblock %}

{% block header_nav_collapse_right %}
  {{ block.super }}
  <div class="gap-1">
    <form method="post" class="d-inline">
      {% csrf_token %}
      <button type="submit" name="refresh" class="btn btn-warning me-2">
        {% trans "Refresh Items" %}
      </button>
    </form>
    <form method="post" class="d-inline">
      {% csrf_token %}
      <button type="submit" name="refresh_contracts" class="btn btn-warning">
        {% trans "Refresh Contracts" %}
      </button>
    </form>
    <form method="get" class="d-inline" action="{% url 'markettracker:character_login_manage' %}">
      {% csrf_token %}
      <button type="submit" name="login-market" class="btn btn-success">
        {% trans "Log in with Market Scope Character" %}
      </button>
    </form>
  </div>
{% endblock %}

{% block content %}

{% if market_character %}
  <div class="d-flex align-items-center mb-3">
    <img src="https://images.evetech.net/characters/{{ market_character.character.character.character_id }}/portrait?size=64"
         class="rounded me-2"
         alt="{{ market_character.character.character.character_name }}">
    <div>
      <div class="fw-bold">{{ market_character.character.character.character_name }}</div>
    </div>
  </div>
{% endif %}

{# ============ ITEMS FORM ============ #}
{% if form %}
  <h1 class="mb-4">{% trans "Add/Edit Item" %}</h1>
  <form method="post" class="mb-4">
    {% csrf_token %}
    {{ form.as_p }}
    {% if form.instance.pk %}
      <input type="hidden" name="item_id" value="{{ form.instance.pk }}">
      <button type="submit" name="edit" class="btn btn-primary">💾 {% trans "Save" %}</button>
    {% else %}
      <button type="submit" name="add" class="btn btn-success">➕ {% trans "Add" %}</button>
    {% endif %}
    <a href="{% url 'markettracker:manage_stock' %}" class="btn btn-secondary">{% trans "Cancel" %}</a>
  </form>

{# ============ CONTRACTS ADD/EDIT FORM (na tej samej stronie) ============ #}
{% elif tc_add_mode and tc_form or tc_edit_id and tc_form %}
  <h1 class="mb-3">
    {% if tc_edit_id %}{% trans "Edit Tracked Contract" %}{% else %}{% trans "Add Tracked Contract" %}{% endif %}
  </h1>

  <form method="post" class="row g-3">
    {% csrf_token %}
    {% if tc_edit_id %}
      <input type="hidden" name="tc_id" value="{{ tc_edit_id }}">
      <input type="hidden" name="tc_edit_submit" value="1">
    {% else %}
      <input type="hidden" name="tc_add_submit" value="1">
    {% endif %}

    <div class="col-12 col-md-3">
      <label class="form-label">{% trans "Tracking type" %}</label>
      {{ tc_form.mode }}
    </div>

    <div class="col-12 col-md-4" id="row-title-filter">
      <label class="form-label">{% trans "Title contains" %}</label>
      {{ tc_form.title_filter }}
    </div>

    <div class="col-12 col-md-4" id="row-fitting">
      <label class="form-label">{% trans "Doctrine fitting" %}</label>
      {{ tc_form.fitting }}
    </div>

    <div class="col-12 col-md-3">
      <label class="form-label">{% trans "Desired contracts" %}</label>
      {{ tc_form.desired_quantity }}
    </div>

    <div class="col-12 col-md-3">
      <label class="form-label">{% trans "Max price (ISK)" %}</label>
      {{ tc_form.max_price }}
    </div>

    <div class="col-12 d-flex gap-2">
      {% if tc_edit_id %}
        <button type="submit" class="btn btn-primary">💾 {% trans "Save" %}</button>
      {% else %}
        <button type="submit" class="btn btn-success">➕ {% trans "Add" %}</button>
      {% endif %}
      <a href="{% url 'markettracker:manage_stock' %}" class="btn btn-secondary">{% trans "Cancel" %}</a>
    </div>
  </form>

  <script>
    (function() {
      const modeSel = document.getElementById("id_mode");
      const rowTitle = document.getElementById("row-title-filter");
      const rowFitting = document.getElementById("row-fitting");

      function toggleFields() {
        const v = modeSel.value;
        if (v === "custom") {
          rowTitle.style.display = "";
          rowFitting.style.display = "none";
        } else {
          rowTitle.style.display = "none";
          rowFitting.style.display = "";
        }
      }

      if (modeSel) {
        toggleFields();
        modeSel.addEventListener("change", toggleFields);
      }
    })();
  </script>

{# ============ NORMALNY WIDOK Z LISTAMI ============ #}
{% else %}
  <h1 class="mb-4">{% trans "Manage Stock" %}</h1>

  {# ITEMS CARD #}
  <div class="card mt-3">
    <div class="card-header d-flex justify-content-between align-items-center">
      <strong>{% trans "Tracked Items" %}</strong>
      <form method="get" class="d-flex gap-2 mb-0">
        <input type="text" name="q" value="{{ q }}" class="form-control form-control-sm" placeholder="{% trans 'Search item...' %}">
        <button class="btn btn-primary btn-sm" type="submit">{% trans "Search" %}</button>
        <a href="?add=1" class="btn btn-success btn-sm">{% trans "Add" %}</a>
      </form>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped mb-0 w-100">
          <thead>
            <tr>
              <th>{% trans "Icon" %}</th>
              <th>{% trans "Item Name" %}</th>
              <th>{% trans "Desired Quantity" %}</th>
              <th class="text-end"></th>
            </tr>
          </thead>
          <tbody>
            {% for item in tracked_items %}
              <tr>
                <td><img src="https://images.evetech.net/types/{{ item.item.id }}/icon" alt="{% trans 'icon' %}" width="32"></td>
                <td>{{ item.item.name }}</td>
                <td>{{ item.desired_quantity|default:"—" }}</td>
                <td class="text-end">
                  <a href="?edit_id={{ item.id }}" class="btn btn-sm btn-secondary">✏️ {% trans "Edit" %}</a>
                  <form method="post" action="{% url 'markettracker:delete_trackeditem' item.id %}" class="d-inline">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-sm btn-danger">🗑️ {% trans "Delete" %}</button>
                  </form>
                </td>
              </tr>
            {% empty %}
              <tr><td colspan="4">{% trans "No items to display." %}</td></tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  {# CONTRACTS CARD #}
  <div class="card mt-4">
    <div class="card-header d-flex justify-content-between align-items-center">
      <strong>{% trans "Tracked Contracts" %}</strong>
      <form method="get" class="d-flex gap-2 mb-0">
        <input type="text" name="cq" value="{{ cq }}" class="form-control form-control-sm" placeholder="{% trans 'Search by ship/fit/title…' %}">
        <button class="btn btn-primary btn-sm" type="submit">{% trans "Search" %}</button>
        <a href="?tc_add=1" class="btn btn-success btn-sm">{% trans "Add" %}</a>
      </form>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped mb-0 w-100">
          <thead>
            <tr>
              <th>{% trans "Type" %}</th>
              <th>{% trans "Name / Filter" %}</th>
              <th>{% trans "Desired" %}</th>
              <th>{% trans "Max price" %}</th>
              <th class="text-end">{% trans "Actions" %}</th>
            </tr>
          </thead>
          <tbody>
            {% for tc in tracked_contracts %}
              <tr>
                <td>
                  {% if tc.mode == "custom" %}
                    <span class="badge bg-info">{% trans "Custom" %}</span>
                  {% else %}
                    <span class="badge bg-secondary">{% trans "Doctrine" %}</span>
                  {% endif %}
                </td>
                <td>
                  {% if tc.mode == "custom" %}
                    {{ tc.title_filter|default:"—" }}
                  {% else %}
                    {% if tc.fitting %}
                      {{ tc.fitting.name }} <span class="text-muted">({{ tc.fitting.ship_type.name }})</span>
                    {% else %}
                      <span class="badge bg-danger">{% trans "Missing fitting" %}</span>
                    {% endif %}
                  {% endif %}
                </td>
                <td>{{ tc.desired_quantity|default:"—" }}</td>
                <td>
                  {% if tc.max_price and tc.max_price|floatformat != "0" %}
                    {{ tc.max_price|floatformat:2|intcomma }} ISK
                  {% else %}
                    <span class="text-muted">—</span>
                  {% endif %}
                </td>
                <td class="text-end">
                  <a href="?tc_edit={{ tc.id }}" class="btn btn-sm btn-secondary">
                    ✏️ {% trans "Edit" %}
                  </a>
                  <form method="post" action="{% url 'markettracker:tracked_contract_delete' tc.id %}" class="d-inline">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-sm btn-danger">                            
                      🗑️ {% trans "Delete" %}
                    </button>
                  </form>
                </td>
              </tr>
            {% empty %}
              <tr>
                <td colspan="5" class="text-center text-muted py-4">{% trans "No tracked contracts yet." %}</td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

{% endif %}
{% endblock %}
