{% extends "admin/change_list.html" %}
{% load i18n admin_urls static %}

{% block object-tools-items %}
  <li>
    <a href="#" class="addlink" onclick="document.getElementById('csv-import-form').style.display='block'; return false;">
      Import from CSV
    </a>
  </li>
  {{ block.super }}
{% endblock %}

{% block content %}
  <div id="csv-import-form" style="display:none; background: #f8f8f8; padding: 20px; margin: 20px 0; border: 1px solid #ddd;">
    <h2>Import Industries from CSV</h2>
    <form method="post" enctype="multipart/form-data" action="{% url 'admin_industry_csv_import' %}" id="csv-upload-form">
      {% csrf_token %}
      <p>
        <label for="csv_file">Select CSV file:</label>
        <input type="file" name="csv_file" id="csv_file" accept=".csv" required>
      </p>
      <p>
        <strong>CSV Format:</strong> name, description, is_active<br>
        <em>Note: Slug will be auto-generated from name</em><br>
        <a href="{% url 'admin_industry_csv_template' %}" download>Download template with examples</a>
      </p>
      <p>
        <button type="submit" class="button">Upload and Import</button>
        <button type="button" class="button" onclick="document.getElementById('csv-import-form').style.display='none'">Cancel</button>
      </p>
    </form>
    <div id="import-results"></div>
  </div>
  
  <script>
    document.getElementById('csv-upload-form').addEventListener('submit', function(e) {
      e.preventDefault();
      
      var formData = new FormData(this);
      var resultsDiv = document.getElementById('import-results');
      resultsDiv.innerHTML = '<p>Importing...</p>';
      
      fetch('{% url "admin_industry_csv_import" %}', {
        method: 'POST',
        body: formData,
        headers: {
          'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        }
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          resultsDiv.innerHTML = '<p style="color: green;">✓ Import successful!<br>' +
            'Created: ' + data.created + '<br>' +
            'Updated: ' + data.updated + '<br>' +
            (data.errors.length > 0 ? 'Errors: ' + data.errors.join('<br>') : '') +
            '</p>';
          setTimeout(function() {
            window.location.reload();
          }, 2000);
        } else {
          resultsDiv.innerHTML = '<p style="color: red;">✗ Error: ' + data.error + '</p>';
        }
      })
      .catch(error => {
        resultsDiv.innerHTML = '<p style="color: red;">✗ Error: ' + error + '</p>';
      });
    });
  </script>
  
  {{ block.super }}
{% endblock %}
