{% extends "base.html" %}
{% block title %}Upload | ECDA LLM{% endblock %}
{% block body_class %}upload{% endblock %}

{% block content %}
<div class="card card-col upload-card">
    <div class="chat-header">
        <h2>Upload documents</h2>

        <div class="tooltip-container">
            <a class="btn btn-ghost" href="/">Home</a>
            <span class="tooltip">Back to Home</span>
        </div>
    </div>

    <p class="meta">
        Upload PDF, TXT, or DOCX files. You can select multiple files.
    </p>

    <form id="uploadForm" class="upload-form" novalidate>
        <div class="file-upload">
            <label for="fileInput" class="file-upload-label">Choose documents</label>

            <input id="fileInput" type="file" multiple
                accept=".pdf,.txt,.docx,application/pdf,text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />

            <div id="fileNames" class="file-names">No files selected</div>
        </div>

        <div class="upload-actions">
            <!-- Upload = ONLY list selected files (NO API call) -->

            <div class="tooltip-container">
                <button id="uploadBtn" class="btn" type="button">Upload</button>
                <span class="tooltip">Upload the files</span>
            </div>

            <div class="tooltip-container">
                <button id="skipBtn" class="btn btn-ghost" type="button">Skip</button>
                <span class="tooltip">Go to chat</span>
            </div>


            <!-- Proceed = DOES upload+embed (API call + Swal) -->
            <div class="tooltip-container">
                <button id="proceedBtn" class="btn btn-proceed" type="button" disabled>Proceed</button>
                <span class="tooltip">First push Upload</span>
            </div>
        </div>
    </form>

    <div id="uploadedList" class="uploaded-list"></div>
</div>

<script>
    // Elements
    const fileInput = document.getElementById("fileInput");
    const fileNames = document.getElementById("fileNames");
    const form = document.getElementById("uploadForm");
    const uploadedList = document.getElementById("uploadedList");
    const skipBtn = document.getElementById("skipBtn");
    const proceedBtn = document.getElementById("proceedBtn");
    const uploadBtn = document.getElementById("uploadBtn");

    // Config from sessionStorage
    const baseUrl = sessionStorage.getItem("LLM_BASE_URL");
    const apiKey = sessionStorage.getItem("LLM_API_KEY") || "lm-studio";
    const model = sessionStorage.getItem("LLM_MODEL");
    const embedModel = sessionStorage.getItem("EMBED_MODEL") || "nomic-embed-text-v1.5";

    if (!baseUrl || !model) window.location.href = "/";

    // Prevent accidental submit (Enter key etc.)
    form.addEventListener("submit", (e) => e.preventDefault());

    // State
    let pendingFiles = []; // selected, not uploaded yet
    let serverFiles = [];  // already uploaded (from /api/uploads)

    function setProceedEnabled(enabled) {
        proceedBtn.disabled = !enabled;
    }

    function escapeHtml(str) {
        return String(str || "")
            .replaceAll("&", "&amp;")
            .replaceAll("<", "&lt;")
            .replaceAll(">", "&gt;")
            .replaceAll('"', "&quot;")
            .replaceAll("'", "&#039;");
    }

    function refreshFileNames() {
        if (!pendingFiles.length) {
            fileNames.textContent = "No files selected";
            return;
        }
        fileNames.textContent = pendingFiles.map(f => f.name).join(" • ");
    }

    // write pendingFiles back into fileInput.files (so Proceed uploads ONLY remaining)
    function syncInputFilesFromPending() {
        const dt = new DataTransfer();
        pendingFiles.forEach(f => dt.items.add(f));
        fileInput.files = dt.files;
    }

    // ----------------------------
    // RENDER: always show BOTH sections
    // ----------------------------
    function renderAll() {
        uploadedList.innerHTML = "";

        // Section 1: already uploaded
        if (serverFiles.length) {
            const title1 = document.createElement("div");
            title1.className = "meta";
            title1.textContent = "Uploaded files:";
            uploadedList.appendChild(title1);

            const ul1 = document.createElement("ul");
            ul1.className = "uploaded-ul";

            serverFiles.forEach((f) => {
                const li = document.createElement("li");
                li.className = "uploaded-li";

                const safeName = escapeHtml(f.original || "");
                const sizeKb = Math.round((f.size || 0) / 1024);

                li.innerHTML = `<span class="uploaded-name">${safeName} (${sizeKb} KB)</span>`;
                ul1.appendChild(li);
            });

            uploadedList.appendChild(ul1);
        }

        // Section 2: pending (selected, not uploaded yet)
        if (pendingFiles.length) {
            const title2 = document.createElement("div");
            title2.className = "meta";
            title2.style.marginTop = "12px";
            title2.textContent = "Selected files (not uploaded yet):";
            uploadedList.appendChild(title2);

            const ul2 = document.createElement("ul");
            ul2.className = "uploaded-ul";

            pendingFiles.forEach((f, idx) => {
                const li = document.createElement("li");
                li.className = "uploaded-li";

                const safeName = escapeHtml(f.name);
                const sizeKb = Math.round((f.size || 0) / 1024);

                li.innerHTML = `
            <span class="uploaded-name">${safeName} (${sizeKb} KB)</span>
            <span class="delete-filename" role="button" tabindex="0" title="Remove">
              <i class="fas fa-trash-alt"></i>
            </span>
          `;

                const del = li.querySelector(".delete-filename");
                del.addEventListener("click", () => {
                    pendingFiles.splice(idx, 1);
                    syncInputFilesFromPending();
                    refreshFileNames();
                    renderAll();
                    setProceedEnabled(pendingFiles.length > 0);
                });

                del.addEventListener("keydown", (e) => {
                    if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        del.click();
                    }
                });

                ul2.appendChild(li);
            });

            uploadedList.appendChild(ul2);
        }

        // Proceed enabled only when there are pending files
        setProceedEnabled(pendingFiles.length > 0);

        // If nothing at all, clear area
        if (!serverFiles.length && !pendingFiles.length) {
            uploadedList.textContent = "";
        }
    }

    // ----------------------------
    // Load uploaded files on refresh
    // ----------------------------
    async function loadExistingUploads() {
        try {
            const res = await fetch("/api/uploads");
            const data = await res.json();
            if (!res.ok || !data.ok) return;
            serverFiles = data.files || [];
            renderAll();
        } catch (e) {
            console.warn("Could not load existing uploads", e);
        }
    }

    // ----------------------------
    // Events
    // ----------------------------
    fileInput.addEventListener("change", () => {
        if (!fileInput.files || fileInput.files.length === 0) {
            pendingFiles = [];
            refreshFileNames();
            renderAll();
            return;
        }

        pendingFiles = Array.from(fileInput.files);
        refreshFileNames();

        // User must click Upload to show pending list (optional rule)
        setProceedEnabled(false);
    });

    uploadBtn.addEventListener("click", () => {
        if (!pendingFiles.length) {
            Swal.fire({ icon: "info", title: "No files selected", text: "Choose files first." });
            return;
        }
        renderAll();                 // ✅ now it will show pending WITHOUT removing server list
        setProceedEnabled(true);
    });

    skipBtn.addEventListener("click", () => (window.location.href = "/chat"));

    // Proceed uploads pending files
    async function doUploadAndEmbed() {
        if (!pendingFiles.length) {
            Swal.fire({ icon: "info", title: "No files selected", text: "Choose files first." });
            return;
        }

        syncInputFilesFromPending();

        const fd = new FormData();
        for (const f of pendingFiles) fd.append("files", f);

        Swal.fire({
            title: "Uploading & embedding…",
            text: "Saving files and indexing into ChromaDB (FastEmbed).",
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading(),
        });

        try {
            const res = await fetch("/api/upload", {
                method: "POST",
                headers: {
                    "X-LLM-Base-URL": baseUrl,
                    "X-LLM-API-Key": apiKey,
                    "X-LLM-Model": model,
                    "X-Embed-Model": embedModel,
                },
                body: fd,
            });

            let data;
            try { data = await res.json(); }
            catch { data = { ok: false, detail: await res.text() }; }

            if (!res.ok || !data.ok) {
                await Swal.fire({
                    icon: "error",
                    title: "Upload failed",
                    text: data.detail || data.message || "Unknown error",
                });
                return;
            }

            // clear pending selection UI
            pendingFiles = [];
            fileInput.value = "";
            fileNames.textContent = "No files selected";

            // IMPORTANT: reload server list so old + new all show
            await loadExistingUploads();

            await Swal.fire({
                icon: "success",
                title: "Uploaded!",
                text: "Documents indexed.",
                timer: 900,
                showConfirmButton: false,
            });

            // keep your redirect if you want:
            window.location.href = "/chat";

        } catch (err) {
            await Swal.fire({ icon: "error", title: "Network error", text: String(err) });
        }
    }

    proceedBtn.addEventListener("click", doUploadAndEmbed);

    // Initial load (on refresh)
    loadExistingUploads();
</script>



{% endblock %}