{% extends "framework_modern.html" %}
{% load static %}
{% block content %}
  <div class="mx-auto w-full p-8">
    <h1 class="h1 mb-4 text-3xl font-bold">Batch Predict Pathways</h1>
    <form id="smiles-form" method="POST" action="{% url "jobs" %}">
      {% csrf_token %}
      <input type="hidden" name="substrates" id="substrates" />
      <input type="hidden" name="job-name" value="batch-predict" />

      <fieldset class="flex flex-col gap-4 md:flex-3/4">
        <!-- CSV Upload Section -->
        <div class="mb-6 rounded-lg border-2 border-dashed border-base-300 p-6">
          <div class="flex flex-col gap-4">
            <div
              class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
            >
              <div class="flex-1">
                <h3 class="text-base font-medium text-base-content mb-1">
                  Load from CSV
                </h3>
                <p class="text-sm text-base-content/70">
                  Upload a CSV file with SMILES and name columns, or insert
                  manually in the table below
                </p>
              </div>
              <div class="flex-shrink-0">
                <input
                  type="file"
                  id="csv-file"
                  accept=".csv,.txt"
                  class="file-input file-input-bordered file-input-sm w-full sm:w-auto"
                />
              </div>
            </div>
            <div
              class="text-xs text-base-content/50 border-t border-base-300 pt-3"
            >
              <strong>Format:</strong> First column = SMILES, Second column =
              Name (headers optional) • Maximum
              {{ batch_predict_max_compoundss|default:150 }} rows
            </div>
          </div>
        </div>

        <table class="table table-zebra w-full">
          <thead>
            <tr>
              <th>SMILES</th>
              <th>Name</th>
            </tr>
          </thead>
          <tbody id="smiles-table-body">
            <tr>
              <td>
                <label>
                  <input
                    type="text"
                    class="input input-bordered w-full smiles-input"
                    placeholder="CN1C=NC2=C1C(=O)N(C(=O)N2C)C"
                    {% if meta.debug %}
                      value="CN1C=NC2=C1C(=O)N(C(=O)N2C)C"
                    {% endif %}
                  />
                </label>
              </td>
              <td>
                <label>
                  <input
                    type="text"
                    class="input input-bordered w-full name-input"
                    placeholder="Caffeine"
                    {% if meta.debug %}
                      value="Caffeine"
                    {% endif %}
                  />
                </label>
              </td>
            </tr>
            <tr>
              <td>
                <label>
                  <input
                    type="text"
                    class="input input-bordered w-full smiles-input"
                    placeholder="CC(C)CC1=CC=C(C=C1)C(C)C(=O)O"
                    {% if meta.debug %}
                      value="CC(C)CC1=CC=C(C=C1)C(C)C(=O)O"
                    {% endif %}
                  />
                </label>
              </td>
              <td>
                <label>
                  <input
                    type="text"
                    class="input input-bordered w-full name-input"
                    placeholder="Ibuprofen"
                    {% if meta.debug %}
                      value="Ibuprofen"
                    {% endif %}
                  />
                </label>
              </td>
            </tr>
          </tbody>
        </table>
        <label class="select mb-2 w-full">
          <span class="label">Predictor</span>
          <select id="prediction-setting" name="prediction-setting">
            <option disabled>Select a Setting</option>
            {% for s in meta.available_settings %}
              <option
                value="{{ s.url }}"
                {% if s.id == meta.user.default_setting.id %}selected{% endif %}
              >
                {{ s.name }}{% if s.id == meta.user.default_setting.id %}
                  (User default)
                {% endif %}
              </option>
            {% endfor %}
          </select>
        </label>
        <label class="floating-label" for="num-tps">
          <input
            type="number"
            name="num-tps"
            value="50"
            step="1"
            min="1"
            max="100"
            id="num-tps"
            class="input input-md w-full"
          />
          <span>Max Transformation Products</span>
        </label>
        <div class="flex justify-end gap-2">
          <button type="button" id="add-row-btn" class="btn btn-outline">
            Add row
          </button>
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      </fieldset>
    </form>
  </div>

  <script>
    const tableBody = document.getElementById("smiles-table-body");
    const addRowBtn = document.getElementById("add-row-btn");
    const csvFileInput = document.getElementById("csv-file");
    const form = document.getElementById("smiles-form");
    const hiddenField = document.getElementById("substrates");

    // Function to create a new table row
    function createTableRow(
      smilesValue = "",
      nameValue = "",
      placeholder = true,
    ) {
      const row = document.createElement("tr");

      const tdSmiles = document.createElement("td");
      const tdName = document.createElement("td");

      const smilesInput = document.createElement("input");
      smilesInput.type = "text";
      smilesInput.className = "input input-bordered w-full smiles-input";
      smilesInput.placeholder = placeholder ? "SMILES" : "";
      smilesInput.value = smilesValue;

      const nameInput = document.createElement("input");
      nameInput.type = "text";
      nameInput.className = "input input-bordered w-full name-input";
      nameInput.placeholder = placeholder ? "Name" : "";
      nameInput.value = nameValue;

      const smilesLabel = document.createElement("label");
      smilesLabel.appendChild(smilesInput);
      tdSmiles.appendChild(smilesLabel);

      const nameLabel = document.createElement("label");
      nameLabel.appendChild(nameInput);
      tdName.appendChild(nameLabel);

      row.appendChild(tdSmiles);
      row.appendChild(tdName);

      return row;
    }

    // Function to clear the table
    function clearTable() {
      tableBody.innerHTML = "";
    }

    // Function to populate table from CSV data
    function populateTableFromCSV(csvData) {
      const lines = csvData.trim().split("\n");
      const maxRows = Number("{{ batch_predict_max_compounds|default:150 }}");
      // Clear existing table
      clearTable();

      // Skip header row if it looks like headers
      const startIndex =
        lines.length > 0 &&
        (lines[0].toLowerCase().includes("smiles") ||
          lines[0].toLowerCase().includes("name"))
          ? 1
          : 0;

      let rowCount = 0;
      for (let i = startIndex; i < lines.length && rowCount < maxRows; i++) {
        const line = lines[i].trim();
        if (!line) continue;

        // Parse CSV line - split by comma, first part is SMILES, rest is name
        const firstCommaIndex = line.indexOf(",");
        let smiles = "";
        let name = "";

        if (firstCommaIndex === -1) {
          // No comma found, treat entire line as SMILES
          smiles = line.trim().replace(/^"(.*)"$/, "$1");
        } else {
          // Split at first comma only
          smiles = line
            .substring(0, firstCommaIndex)
            .trim()
            .replace(/^"(.*)"$/, "$1");
          name = line
            .substring(firstCommaIndex + 1)
            .trim()
            .replace(/^"(.*)"$/, "$1");
        }

        // Skip empty rows
        if (!smiles && !name) continue;

        const row = createTableRow(smiles, name, false);
        tableBody.appendChild(row);
        rowCount++;
      }

      // Add at least one empty row if no data was loaded
      if (rowCount === 0) {
        const row = createTableRow();
        tableBody.appendChild(row);
      }

      // Show success message
      if (rowCount > 0) {
        const message =
          rowCount >= maxRows
            ? `Loaded ${rowCount} rows (maximum reached)`
            : `Loaded ${rowCount} rows from CSV`;

        // Create temporary success notification
        const notification = document.createElement("div");
        notification.className = "alert alert-success mb-4";
        notification.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <span>${message}</span>
    `;

        // Insert notification before the table
        const tableContainer = document.querySelector("table").parentNode;
        tableContainer.insertBefore(
          notification,
          document.querySelector("table"),
        );

        // Remove notification after 3 seconds
        setTimeout(() => {
          if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
          }
        }, 3000);
      }
    }
    // Handle CSV file selection
    csvFileInput.addEventListener("change", function (event) {
      const file = event.target.files[0];
      if (!file) return;

      // Check file type
      if (!file.name.match(/\.(csv|txt)$/i)) {
        alert("Please select a CSV or TXT file.");
        return;
      }

      const reader = new FileReader();
      reader.onload = function (e) {
        try {
          populateTableFromCSV(e.target.result);
        } catch (error) {
          console.error("Error parsing CSV:", error);
          alert("Error parsing CSV file. Please check the file format.");
        }
      };
      reader.readAsText(file);
    });

    // Handle add row button
    addRowBtn.addEventListener("click", () => {
      const row = createTableRow();
      tableBody.appendChild(row);
    });

    // Before submit, gather table data into the hidden field
    form.addEventListener("submit", (e) => {
      const smilesInputs = Array.from(
        document.querySelectorAll(".smiles-input"),
      );
      const nameInputs = Array.from(document.querySelectorAll(".name-input"));

      const lines = [];

      for (let i = 0; i < smilesInputs.length; i++) {
        const smiles = smilesInputs[i].value.trim();
        const name = nameInputs[i]?.value.trim() ?? "";

        // Skip empty rows
        if (!smiles && !name) {
          continue;
        }
        lines.push(`${smiles},${name}`);
      }
      // Value looks like:
      // "CN1C=NC2=C1C(=O)N(C(=O)N2C)C,Caffeine\nCC(C)CC1=CC=C(C=C1)C(C)C(=O)O,Ibuprofen"
      hiddenField.value = lines.join("\n");
    });
  </script>
{% endblock content %}
