{% extends 'core/base.html' %}
{% block title %}View Entries – Nature In Pots{% endblock %}

{% block content %}
  <!-- BETA NOTICE -->
  <div class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>Heads up!</strong> We’re in alpha, do not share the main system for the time being as this is not on a reliable host.
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>Heads up!</strong> We’re in alpha – expect occasional hiccups, use the zip backup. 
    <br /><strong>Also</strong>, QR codes work but generation will change more soon to be more user friendly.
    <br /><strong>Update</strong>, QR Card is public, direct is private. Do not use this for sharing currently please.
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>

  <h2 class="mb-4">View Entries</h2>

  {# ── Import / Export / Stats & Filters / View Toggle ───────────────────── #}
  <div class="mb-3 d-flex flex-wrap justify-content-between align-items-start">
    {# LEFT: Import/Export + Stats toggles #}
    <div class="btn-toolbar mb-2" role="toolbar">
      <div class="btn-group me-2" role="group">
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#importModal">
          Import CSV
        </button>
      </div>

      <div class="btn-group me-2" role="group">
        <a href="{{ url_for('utility.export_data') }}" class="btn btn-secondary">
          Export My Data
        </a>
        <button
          class="btn btn-secondary d-inline-block d-md-none"
          data-bs-toggle="modal"
          data-bs-target="#statsModal">
          Stats
        </button>
        <button
          class="btn btn-secondary d-none d-md-inline-block"
          data-bs-toggle="collapse"
          data-bs-target="#statsBox"
          aria-expanded="false"
          aria-controls="statsBox"
          id="statsToggle">
          Stats <i class="bi bi-chevron-down"></i>
        </button>
      </div>
    </div>

    {# RIGHT: filter form + view toggle #}
    <form
      method="get"
      action="{{ url_for('plant.index') }}"
      class="row gx-2 gy-2 align-items-center mb-2"
    >
      <div class="col-auto">
        <div class="input-group">
          <span class="input-group-text">Search</span>
          <input
            type="search"
            name="q"
            value="{{ q }}"
            class="form-control"
            placeholder="by name…"
          />
        </div>
      </div>

      <div class="col-auto">
        <select
          name="type"
          class="form-select"
          style="min-width:140px;"
          onchange="this.form.submit()"
        >
          <option value="">All Types</option>
          {% for t in plant_types %}
            <option
              value="{{ t|lower }}"
              {% if t|lower == type_filter %}selected{% endif %}
            >{{ t }}</option>
          {% endfor %}
        </select>
      </div>

      <div class="col-auto">
        <select
          name="per_page"
          class="form-select"
          style="min-width:140px;"
          onchange="this.form.submit()"
        >
          {% for size in [6,12,18,24] %}
            <option value="{{ size }}" {% if per_page == size %}selected{% endif %}>
              {{ size }} per page
            </option>
          {% endfor %}
        </select>
      </div>

      {# preserve current view so Apply doesn’t reset it #}
      <input type="hidden" name="view" value="{{ view_mode }}" />

      <div class="col-auto">
        <button type="submit" class="btn btn-primary">Apply</button>
      </div>

      <div class="col-auto">
        <div class="btn-group" role="group" aria-label="View mode">
          <a
            href="{{ url_for('plant.index',
                              page=pagination.page,
                              per_page=per_page,
                              q=q,
                              type=type_filter,
                              view='grid') }}"
            class="btn btn-outline-secondary {% if view_mode=='grid' %}active{% endif %}"
            title="Card View"
          >
            <i class="bi bi-grid-3x3-gap-fill"></i>
          </a>
          <a
            href="{{ url_for('plant.index',
                              page=pagination.page,
                              per_page=per_page,
                              q=q,
                              type=type_filter,
                              view='list') }}"
            class="btn btn-outline-secondary {% if view_mode=='list' %}active{% endif %}"
            title="List View"
          >
            <i class="bi bi-list-ul"></i>
          </a>
        </div>
      </div>
    </form>
  </div>

  <!-- Stats container (desktop only) -->
  <div class="collapse mb-3" id="statsBox">
    <div class="d-none d-md-block p-3 bg-light border rounded">
      <h5 class="text-center">Statistics</h5>
      <div class="row row-cols-1 row-cols-md-2 g-3 mt-3">
        <div class="col">
          <div class="d-flex flex-column align-items-center">
            <i class="bi bi-flower3 fs-2 text-success mb-2"></i>
            <div class="small text-muted">Your plants</div>
            <div class="fw-bold fs-4">{{ stats.user_plants }}</div>
          </div>
        </div>
        <div class="col">
          <div class="d-flex flex-column align-items-center">
            <i class="bi bi-file-earmark-image fs-2 text-primary mb-2"></i>
            <div class="small text-muted">Your images</div>
            <div class="fw-bold fs-4">{{ stats.user_images }}</div>
          </div>
        </div>
        <div class="col">
          <div class="d-flex flex-column align-items-center">
            <i class="bi bi-tree fs-2 text-success mb-2"></i>
            <div class="small text-muted">Total plants</div>
            <div class="fw-bold fs-4">{{ stats.total_plants }}</div>
          </div>
        </div>
        <div class="col">
          <div class="d-flex flex-column align-items-center">
            <i class="bi bi-images fs-2 text-primary mb-2"></i>
            <div class="small text-muted">Total images</div>
            <div class="fw-bold fs-4">{{ stats.total_images }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Stats Modal (for mobile) -->
  <div class="modal fade" id="statsModal" tabindex="-1" aria-labelledby="statsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="statsModalLabel">Statistics</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row row-cols-1 row-cols-2 g-3">
            <div class="col">
              <div class="d-flex flex-column align-items-center">
                <i class="bi bi-flower3 fs-2 text-success mb-2"></i>
                <div class="small text-muted">Your plants</div>
                <div class="fw-bold fs-4">{{ stats.user_plants }}</div>
              </div>
            </div>
            <div class="col">
              <div class="d-flex flex-column align-items-center">
                <i class="bi bi-file-earmark-image fs-2 text-primary mb-2"></i>
                <div class="small text-muted">Your images</div>
                <div class="fw-bold fs-4">{{ stats.user_images }}</div>
              </div>
            </div>
            <div class="col">
              <div class="d-flex flex-column align-items-center">
                <i class="bi bi-tree fs-2 text-success mb-2"></i>
                <div class="small text-muted">Total plants</div>
                <div class="fw-bold fs-4">{{ stats.total_plants }}</div>
              </div>
            </div>
            <div class="col">
              <div class="d-flex flex-column align-items-center">
                <i class="bi bi-images fs-2 text-primary mb-2"></i>
                <div class="small text-muted">Total images</div>
                <div class="fw-bold fs-4">{{ stats.total_images }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  {# ── Results (list vs grid) ──────────────────────────────────────────── #}
  {% if view_mode=='list' %}
    <div class="list-group">
      {% for plant in plants %}
        <div class="list-group-item py-3">
          <div class="row align-items-center">
            <div class="col-auto">
              {%- set f = (plant.media_items|selectattr('featured')|first)
                         or (plant.media_items|first) -%}
              <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
                <img
                  src="{{ generate_image_url(f) }}"
                  class="img-thumbnail"
                  style="width:80px;height:80px;object-fit:cover;"
                  alt="Image for {{ plant.common_name.name }}"
                >
              </a>
            </div>
            <div class="col">
              <h5 class="mb-1">
                <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
                  {{ plant.common_name.name }}
                </a>
              </h5>
              <small class="text-muted">{{ plant.uuid }}</small>
              <div class="mt-1">
                <span class="badge bg-secondary">{{ plant.plant_type }}</span>
              </div>
            </div>
            <div class="col-auto text-nowrap">
              <a
                href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}"
                class="btn btn-sm btn-primary me-1"
              >View</a>
              <a
                href="{{ url_for('plant.edit', uuid_val=plant.uuid) }}"
                class="btn btn-sm btn-secondary"
              >Edit</a>
            </div>
          </div>
        </div>
      {% endfor %}
    </div>
  {% else %}
    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
      {% for plant in plants %}
        <div class="col">
          <div class="card h-100">
            {%- set f = (plant.media_items|selectattr('featured')|first)
                       or (plant.media_items|first) -%}
            <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
              <img
                src="{{ generate_image_url(f) }}"
                class="card-img-top"
                style="height:200px;object-fit:cover;"
                alt="Image for {{ plant.common_name.name }}"
              >
            </a>
            <div class="card-body d-flex flex-column">
              <h5 class="card-title mb-1">
                <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
                  {{ plant.common_name.name }}
                </a>
              </h5>
              <small class="text-muted mb-2">{{ plant.uuid }}</small>
              <div class="mt-auto">
                <a
                  href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}"
                  class="btn btn-sm btn-primary me-1"
                >View</a>
                <a
                  href="{{ url_for('plant.edit', uuid_val=plant.uuid) }}"
                  class="btn btn-sm btn-secondary"
                >Edit</a>
              </div>
            </div>
          </div>
        </div>
      {% endfor %}
    </div>
  {% endif %}

  {# ── Pagination ─────────────────────────────────────────────────────── #}
  <nav aria-label="Page navigation" class="mt-4">
    <ul class="pagination justify-content-center">
      <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
        <a
          class="page-link"
          href="{{ url_for('plant.index',
            page=1,
            per_page=per_page,
            q=q,
            type=type_filter,
            view=view_mode
          ) }}"
        >« First</a>
      </li>
      <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
        <a
          class="page-link"
          href="{{ url_for('plant.index',
            page=pagination.prev_num or 1,
            per_page=per_page,
            q=q,
            type=type_filter,
            view=view_mode
          ) }}"
        >‹ Prev</a>
      </li>

      {% set total = pagination.pages %}
      {% set curr  = pagination.page  %}
      {% set w     = 3                 %}
      {% for p in range(1, total+1) %}
        {% if p <= w or p > total-w or (p >= curr-1 and p <= curr+1) %}
          <li class="page-item {% if p==curr %}active{% endif %}">
            <a
              class="page-link"
              href="{{ url_for('plant.index',
                page=p,
                per_page=per_page,
                q=q,
                type=type_filter,
                view=view_mode
              ) }}"
            >{{ p }}</a>
          </li>
        {% elif p == w+1 or p == total-w %}
          <li class="page-item disabled"><span class="page-link">…</span></li>
        {% endif %}
      {% endfor %}

      <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
        <a
          class="page-link"
          href="{{ url_for('plant.index',
            page=pagination.next_num or total,
            per_page=per_page,
            q=q,
            type=type_filter,
            view=view_mode
          ) }}"
        >Next ›</a>
      </li>
      <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
        <a
          class="page-link"
          href="{{ url_for('plant.index',
            page=total,
            per_page=per_page,
            q=q,
            type=type_filter,
            view=view_mode
          ) }}"
        >Last »</a>
      </li>
    </ul>
  </nav>
{% endblock %}

{% block scripts %}
  {{ super() }}
  <script>
    // Toggle chevron icon on desktop collapse
    const statsBox = document.getElementById('statsBox');
    statsBox.addEventListener('shown.bs.collapse', () => {
      document.querySelector('#statsToggle i')
              .classList.replace('bi-chevron-down','bi-chevron-up');
    });
    statsBox.addEventListener('hidden.bs.collapse', () => {
      document.querySelector('#statsToggle i')
              .classList.replace('bi-chevron-up','bi-chevron-down');
    });
  </script>
{% endblock %}
