{% extends "core/base.jinja" %}

{% block additional_js %}
  <script type="module" src="{{ static("bundled/core/dynamic-formset-index.ts") }}"></script>
{% endblock %}


{% macro action_form(form) %}
  <fieldset x-data="{action: '{{ form.task.initial }}'}">
    {{ form.non_field_errors() }}
    <div class="row gap-2x margin-bottom">
      <div>
        {{ form.task.errors }}
        {{ form.task.label_tag() }}
        {{ form.task|add_attr("x-model=action") }}
      </div>
      <div>{{ form.trigger_at.as_field_group() }}</div>
    </div>
    <div x-show="action==='counter.tasks.change_counters'" class="margin-bottom">
      {{ form.counters.as_field_group() }}
    </div>
    {%- if form.DELETE -%}
      <div class="row gap">
        {{ form.DELETE.as_field_group() }}
      </div>
    {%- else -%}
      <button
        class="btn btn-grey"
        @click.prevent="removeForm($event.target.closest('fieldset'))"
      >
        <i class="fa fa-minus"></i>{% trans %}Remove this action{% endtrans %}
      </button>
    {%- endif -%}
    {%- for field in form.hidden_fields() -%}
      {{ field }}
    {%- endfor -%}
    <hr />
  </fieldset>
{% endmacro %}


{% block content %}
  {% if object %}
    <h2>{% trans name=object %}Edit product {{ name }}{% endtrans %}</h2>
    <p><i>{% trans %}Creation date{% endtrans %} : {{ object.created_at|date }}</i></p>
    <p><i>{% trans %}Last update{% endtrans %} : {{ object.updated_at|date }}</i></p>
  {% else %}
    <h2>{% trans %}Product creation{% endtrans %}</h2>
  {% endif %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p() }}

    <br />

    <h3>{% trans %}Automatic actions{% endtrans %}</h3>

    <p class="margin-bottom">
      <em>
        {%- trans trimmed -%}
          Automatic actions allows to schedule product changes
          ahead of time.
        {%- endtrans -%}
      </em>
    </p>

    <div x-data="dynamicFormSet" class="margin-bottom">
      {{ form.action_formset.management_form }}
      <div x-ref="formContainer">
        {%- for f in form.action_formset.forms -%}
          {{ action_form(f) }}
        {%- endfor -%}
      </div>
      <template x-ref="formTemplate">
        {{ action_form(form.action_formset.empty_form) }}
      </template>
      <button @click.prevent="addForm()" class="btn btn-grey">
        <i class="fa fa-plus"></i>{% trans %}Add action{% endtrans %}
      </button>
    </div>
    <p><input class="btn btn-blue" type="submit" value="{% trans %}Save{% endtrans %}" /></p>
  </form>
{% endblock %}