{% extends 'core_ui/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>

  <!-- Stats container (desktop only, collapsed by default) -->
  <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>

  <h2>View Entries</h2>

  <!-- Import / Export & Filter bar -->
  <div class="mb-3 d-flex flex-wrap justify-content-between align-items-center">
    <div class="mb-2 d-flex align-items-center">
      <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#importModal">
        Import CSV
      </button>
      <a href="{{ url_for('utility.export_data') }}" class="btn btn-secondary me-2">Export My Data</a>
      <button
        class="btn btn-secondary me-2 d-inline-block d-md-none"
        data-bs-toggle="modal"
        data-bs-target="#statsModal">
        Stats
      </button>
      <button
        class="btn btn-secondary me-2 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 class="d-flex flex-wrap flex-md-nowrap align-items-center">
      <div class="input-group me-2 mb-2 mb-md-0" style="min-width:200px;">
        <span class="input-group-text">Search</span>
        <input id="searchInput" type="text" class="form-control" placeholder="by name…">
      </div>
      <select id="typeFilter" class="form-select me-2 mb-2 mb-md-0" style="min-width:140px;">
        <option value="">All Types</option>
        {% for t in plant_types %}
          <option value="{{ t|lower }}">{{ t }}</option>
        {% endfor %}
      </select>
      <select id="pageSizeSelect" class="form-select me-2 mb-2 mb-md-0" style="min-width:140px;">
        {% for size in [6,12,18,24] %}
          <option value="{{ size }}" {% if size == 12 %}selected{% endif %}>
            {{ size }} per page
          </option>
        {% endfor %}
      </select>
    </div>
  </div>

  <!-- Plant cards -->
  <div class="row row-cols-1 row-cols-lg-3 g-3" id="plantContainer">
    {% for plant in plants %}
      <div class="col plant-card"
           data-name="{{ plant.common_name.name|lower }}"
           data-type="{{ plant.plant_type|lower }}">
        <div class="card h-100">
          {% set featured = plant.featured_media %}
          {% if not featured and plant.media %}
            {% set featured = plant.media[0] %}
          {% endif %}

          <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
            {# pick featured → first media if no explicit featured #}
            {% set featured = plant.featured_media %}
            {% if not featured and plant.media %}
              {% set featured = plant.media[0] %}
            {% endif %}
            <img
              src="{{ generate_image_url(featured) }}"
              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">
              <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
                {{ plant.common_name.name }}
              </a>
            </h5>
            <h6 class="text-muted">{{ plant.uuid }}</h6>
            <p class="mb-1"><strong>Type:</strong> {{ plant.plant_type }}</p>
            <p class="mb-1"><strong>Scientific Name:</strong> {{ plant.scientific_name.name }}</p>
            {% if plant.mother_uuid %}
              <p class="mb-1">
                <strong>Mother:</strong>
                <a href="{{ url_for('plant.detail', uuid_val=plant.mother_uuid) }}">
                  {{ plant.mother_uuid }}
                </a>
              </p>
            {% endif %}

            <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 me-1">Edit</a>
              <a href="{{ url_for('utility.download_qr', uuid_val=plant.uuid) }}"
                 class="btn btn-sm btn-outline-primary me-1">Direct QR</a>
              <a href="{{ url_for('utility.download_qr_card', uuid_val=plant.uuid) }}"
                 class="btn btn-sm btn-outline-secondary">Card QR</a>
            </div>
          </div>
        </div>
      </div>
    {% endfor %}
  </div>

  <!-- pagination controls -->
  <nav aria-label="Page navigation" class="mt-4 mb-5">
    <ul class="pagination justify-content-center" id="pagination"></ul>
  </nav>

  <!-- client-side filtering & pagination script -->
  <script>
    (function() {
      const searchInput    = document.getElementById('searchInput');
      const typeFilter     = document.getElementById('typeFilter');
      const pageSizeSelect = document.getElementById('pageSizeSelect');
      const container      = document.getElementById('plantContainer');
      const pagination     = document.getElementById('pagination');
      const cards          = Array.from(container.querySelectorAll('.plant-card'));
      let currentPage = 1;
      let pageSize    = parseInt(pageSizeSelect.value, 10);

      function filterAndPaginate() {
        const q    = searchInput.value.trim().toLowerCase();
        const type = typeFilter.value;
        const filtered = cards.filter(card => {
          return card.dataset.name.includes(q) &&
                 (!type || card.dataset.type === type);
        });

        const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
        if (currentPage > totalPages) currentPage = totalPages;

        cards.forEach(c => c.style.display = 'none');
        const start = (currentPage - 1) * pageSize;
        filtered.slice(start, start + pageSize)
                .forEach(c => c.style.display = '');

        pagination.innerHTML = '';

        // Prev button
        const prevLi = document.createElement('li');
        prevLi.className = 'page-item' + (currentPage === 1 ? ' disabled' : '');
        prevLi.innerHTML = `<a class="page-link" href="#">Prev</a>`;
        prevLi.onclick = e => {
          e.preventDefault();
          if (currentPage > 1) { currentPage--; filterAndPaginate(); }
        };
        pagination.appendChild(prevLi);

        // Page numbers
        if (totalPages <= 5) {
          for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = 'page-item' + (i === currentPage ? ' active' : '');
            li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
            li.onclick = e => {
              e.preventDefault();
              currentPage = i;
              filterAndPaginate();
            };
            pagination.appendChild(li);
          }
        } else {
          [1,2,3].forEach(n => {
            const li = document.createElement('li');
            li.className = 'page-item' + (n === currentPage ? ' active' : '');
            li.innerHTML = `<a class="page-link" href="#">${n}</a>`;
            li.onclick = e => {
              e.preventDefault();
              currentPage = n;
              filterAndPaginate();
            };
            pagination.appendChild(li);
          });
          const ell = document.createElement('li');
          ell.className = 'page-item disabled';
          ell.innerHTML = `<span class="page-link">…</span>`;
          pagination.appendChild(ell);
          const lastLi = document.createElement('li');
          lastLi.className = 'page-item' + (totalPages === currentPage ? ' active' : '');
          lastLi.innerHTML = `<a class="page-link" href="#">${totalPages}</a>`;
          lastLi.onclick = e => {
            e.preventDefault();
            currentPage = totalPages;
            filterAndPaginate();
          };
          pagination.appendChild(lastLi);
        }

        // Next button
        const nextLi = document.createElement('li');
        nextLi.className = 'page-item' + (currentPage === totalPages ? ' disabled' : '');
        nextLi.innerHTML = `<a class="page-link" href="#">Next</a>`;
        nextLi.onclick = e => {
          e.preventDefault();
          if (currentPage < totalPages) { currentPage++; filterAndPaginate(); }
        };
        pagination.appendChild(nextLi);
      }

      // Initialize and bind events
      filterAndPaginate();
      searchInput.addEventListener('input',    () => { currentPage = 1; filterAndPaginate(); });
      typeFilter.addEventListener('change',    () => { currentPage = 1; filterAndPaginate(); });
      pageSizeSelect.addEventListener('change',() => {
        pageSize = parseInt(pageSizeSelect.value, 10);
        currentPage = 1; filterAndPaginate();
      });
    })();
  </script>

  <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 %}
