document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("generator-form");
    const results = document.getElementById("question-results");
    const progress = document.getElementById("generation-progress");
    const editPanel = document.getElementById("edit-panel");

    if (!form) {
        alert("Form not found");
        return;
    }

    function renderQuestionCard(q) {
        if (results.innerHTML.includes("No questions generated yet.")) {
            results.innerHTML = "";
        }

        const card = `
            <div class="question-card">
                <h3>${q.title}</h3>
                <p><strong>Status:</strong> ${q.status || "Draft"}</p>
                <p><strong>Tags:</strong> ${q.skill} | ${q.specialty} | ${q.condition_name} | ${q.presentation}</p>
                <p><strong>Stem:</strong> ${q.stem}</p>
                <p><strong>Lead-in:</strong> ${q.lead_in}</p>
                <ul>
                    <li>A. ${q.option_a}</li>
                    <li>B. ${q.option_b}</li>
                    <li>C. ${q.option_c}</li>
                    <li>D. ${q.option_d}</li>
                    <li>E. ${q.option_e}</li>
                </ul>
                <p><strong>Correct Answer:</strong> ${q.correct_answer_letter} - ${q.correct_answer}</p>
                <p><strong>Justification:</strong> ${q.justification}</p>

                <div class="question-actions">
                    <button type="button" class="edit-btn" data-id="${q.id}">Edit</button>
                    <button type="button" class="mark-done-btn" data-id="${q.id}">Mark Done</button>
                    <button type="button" class="reject-btn" data-id="${q.id}">Reject</button>
                    <button type="button" class="regenerate-btn" data-id="${q.id}">Regenerate</button>
                </div>
            </div>
        `;

        results.innerHTML = card + results.innerHTML;
        attachQuestionActionHandlers();
    }

    function attachQuestionActionHandlers() {
        const doneButtons = document.querySelectorAll(".mark-done-btn");
        const rejectButtons = document.querySelectorAll(".reject-btn");
        const regenerateButtons = document.querySelectorAll(".regenerate-btn");
        const editButtons = document.querySelectorAll(".edit-btn");

        editButtons.forEach(button => {
            button.onclick = function () {
                const questionId = this.getAttribute("data-id");

                fetch(`../app/api/get_question.php?question_id=${questionId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === "success") {
                            editPanel.innerHTML = `
    <p><strong>Editing question ID:</strong> ${data.question.id}</p>

    <label><strong>Title</strong></label><br>
    <input type="text" id="edit-title" value="${data.question.title || ''}" style="width: 100%;"><br><br>

    <label><strong>Stem</strong></label><br>
    <textarea id="edit-stem" rows="6" style="width: 100%;">${data.question.stem || ''}</textarea><br><br>

    <label><strong>Lead-in</strong></label><br>
    <textarea id="edit-lead-in" rows="3" style="width: 100%;">${data.question.lead_in || ''}</textarea><br><br>

    <label><strong>Option A</strong></label><br>
    <input type="text" id="edit-option-a" value="${data.question.option_a || ''}" style="width: 100%;"><br><br>

    <label><strong>Option B</strong></label><br>
    <input type="text" id="edit-option-b" value="${data.question.option_b || ''}" style="width: 100%;"><br><br>

    <label><strong>Option C</strong></label><br>
    <input type="text" id="edit-option-c" value="${data.question.option_c || ''}" style="width: 100%;"><br><br>

    <label><strong>Option D</strong></label><br>
    <input type="text" id="edit-option-d" value="${data.question.option_d || ''}" style="width: 100%;"><br><br>

    <label><strong>Option E</strong></label><br>
    <input type="text" id="edit-option-e" value="${data.question.option_e || ''}" style="width: 100%;"><br><br>

    <label><strong>Correct Answer</strong></label><br>
    <select id="edit-correct-answer" style="width: 100%;">
        <option value="">Select answer</option>
        <option value="A" ${data.question.correct_answer_letter === 'A' ? 'selected' : ''}>A</option>
        <option value="B" ${data.question.correct_answer_letter === 'B' ? 'selected' : ''}>B</option>
        <option value="C" ${data.question.correct_answer_letter === 'C' ? 'selected' : ''}>C</option>
        <option value="D" ${data.question.correct_answer_letter === 'D' ? 'selected' : ''}>D</option>
        <option value="E" ${data.question.correct_answer_letter === 'E' ? 'selected' : ''}>E</option>
    </select><br><br>

    <label><strong>Explanation / Justification</strong></label><br>
    <textarea id="edit-justification" rows="5" style="width: 100%;">${data.question.justification || ''}</textarea><br><br>

    <button type="button" id="save-question-btn" data-id="${data.question.id}">Save Changes</button>
`;
                            const saveButton = document.getElementById("save-question-btn");

saveButton.onclick = function () {
    const questionId = saveButton.getAttribute("data-id");
    const titleField = document.getElementById("edit-title");
    const stemField = document.getElementById("edit-stem");
    const leadInField = document.getElementById("edit-lead-in");
    const optionAField = document.getElementById("edit-option-a");
    const optionBField = document.getElementById("edit-option-b");
    const optionCField = document.getElementById("edit-option-c");
    const optionDField = document.getElementById("edit-option-d");
    const optionEField = document.getElementById("edit-option-e");
    const correctAnswerField = document.getElementById("edit-correct-answer");
    const justificationField = document.getElementById("edit-justification");

    if (!titleField || !stemField || !leadInField || !optionAField || !optionBField || !optionCField || !optionDField || !optionEField || !correctAnswerField || !justificationField) {
        alert("Edit fields not found.");
        return;
    }

    const title = titleField.value;
    const stem = stemField.value;
    const leadIn = leadInField.value;
    const optionA = optionAField.value;
    const optionB = optionBField.value;
    const optionC = optionCField.value;
    const optionD = optionDField.value;
    const optionE = optionEField.value;
    const correctAnswerLetter = correctAnswerField.value;
    const justification = justificationField.value;

    fetch("../app/api/update_question.php", {
        method: "POST",
        body: new URLSearchParams({
            question_id: questionId,
            title: title,
            stem: stem,
            lead_in: leadIn,
            option_a: optionA,
            option_b: optionB,
            option_c: optionC,
            option_d: optionD,
            option_e: optionE,
            correct_answer_letter: correctAnswerLetter,
            justification: justification
        })
    })
                                .then(response => response.json())
                                .then(saveData => {
                                    if (saveData.status === "success") {
                                        alert("Question updated.");
                                        loadExistingQuestions();
                                    } else {
                                        alert(saveData.message);
                                    }
                                })
                                .catch(error => {
                                    console.error(error);
                                    alert("Error saving question.");
                                });
                            };
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => {
                        console.error(error);
                        alert("Error loading question.");
                    });
            };
        });

        doneButtons.forEach(button => {
            button.onclick = function () {
                const questionId = this.getAttribute("data-id");

                fetch("../app/api/update_question_status.php", {
                    method: "POST",
                    body: new URLSearchParams({
                        question_id: questionId,
                        status: "Done"
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === "success") {
                        loadExistingQuestions();
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error(error);
                    alert("Error updating question status.");
                });
            };
        });

        rejectButtons.forEach(button => {
            button.onclick = function () {
                const questionId = this.getAttribute("data-id");

                fetch("../app/api/update_question_status.php", {
                    method: "POST",
                    body: new URLSearchParams({
                        question_id: questionId,
                        status: "Rejected"
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === "success") {
                        loadExistingQuestions();
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error(error);
                    alert("Error updating question status.");
                });
            };
        });

        regenerateButtons.forEach(button => {
            button.onclick = function () {
                const questionId = this.getAttribute("data-id");
                if (!confirm("Are you sure you want to regenerate this question? The current question will be deleted.")) {
                    return;
                }

                fetch("../app/api/delete_question.php", {
                    method: "POST",
                    body: new URLSearchParams({
                        question_id: questionId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === "success") {
                        loadExistingQuestions();
                        startSingleReplacementGeneration();
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error(error);
                    alert("Error deleting question.");
                });
            };
        });
    }

    function generateNextQuestion(jobId) {
        const generateData = new FormData();
        generateData.append("job_id", jobId);

        fetch("../app/api/generate_next_question.php", {
            method: "POST",
            body: generateData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                progress.innerHTML = `<p>Generating questions: ${data.questions_completed} of ${data.num_questions} completed</p>`;
                renderQuestionCard(data.question);

                if (data.job_status === "running") {
                    generateNextQuestion(jobId);
                } else {
                    progress.innerHTML = `<p>Generation complete. ${data.num_questions} question(s) generated.</p>`;
                }
            } else if (data.status === "complete") {
                progress.innerHTML = `<p>Generation complete.</p>`;
            } else {
                progress.innerHTML = `<p>${data.message}</p>`;
            }
        })
        .catch(error => {
            console.error(error);
            progress.innerHTML = `<p>Error generating next question.</p>`;
        });
    }

    function loadExistingQuestions() {
        const workspaceId = localStorage.getItem("workspace_id");

        if (!workspaceId) {
            results.innerHTML = `<p>No questions generated yet.</p>`;
            return;
        }

        fetch(`../app/api/get_workspace_questions.php?workspace_id=${workspaceId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === "success") {
                    results.innerHTML = "";

                    if (data.questions.length === 0) {
                        results.innerHTML = `<p>No questions generated yet.</p>`;
                        return;
                    }

                    data.questions.forEach(q => {
                        const card = `
                            <div class="question-card">
                                <h3>${q.title}</h3>
                                <p><strong>Status:</strong> ${q.status || "Draft"}</p>
                                <p><strong>Tags:</strong> ${q.skill} | ${q.specialty} | ${q.condition_name} | ${q.presentation}</p>
                                <p><strong>Stem:</strong> ${q.stem}</p>
                                <p><strong>Lead-in:</strong> ${q.lead_in}</p>
                                <ul>
                                    <li>A. ${q.option_a}</li>
                                    <li>B. ${q.option_b}</li>
                                    <li>C. ${q.option_c}</li>
                                    <li>D. ${q.option_d}</li>
                                    <li>E. ${q.option_e}</li>
                                </ul>
                                <p><strong>Correct Answer:</strong> ${q.correct_answer_letter} - ${q.correct_answer}</p>
                                <p><strong>Justification:</strong> ${q.justification}</p>

                                <div class="question-actions">
                                    <button type="button" class="edit-btn" data-id="${q.id}">Edit</button>
                                    <button type="button" class="mark-done-btn" data-id="${q.id}">Mark Done</button>
                                    <button type="button" class="reject-btn" data-id="${q.id}">Reject</button>
                                    <button type="button" class="regenerate-btn" data-id="${q.id}">Regenerate</button>
                                </div>
                            </div>
                        `;
                        results.innerHTML += card;
                    });

                    attachQuestionActionHandlers();
                } else {
                    results.innerHTML = `<p>Error loading saved questions.</p>`;
                }
            })
            .catch(error => {
                console.error(error);
                results.innerHTML = `<p>Error loading saved questions.</p>`;
            });
    }

    function startSingleReplacementGeneration() {
        const workspaceId = localStorage.getItem("workspace_id");

        if (!workspaceId) {
            alert("No workspace found.");
            return;
        }

        const formData = new FormData(form);
        formData.append("workspace_id", workspaceId);

        progress.innerHTML = `<p>Starting replacement question...</p>`;

        fetch("../app/api/start_generation_job.php", {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                generateNextQuestion(data.job_id);
            } else {
                progress.innerHTML = `<p>${data.message}</p>`;
            }
        })
        .catch(error => {
            console.error(error);
            progress.innerHTML = `<p>Error starting replacement generation.</p>`;
        });
    }

    form.addEventListener("submit", function (event) {
        event.preventDefault();

        const workspaceId = localStorage.getItem("workspace_id");

        if (!workspaceId) {
            alert("No workspace found.");
            return;
        }

        const formData = new FormData(form);
        formData.append("workspace_id", workspaceId);

        document.getElementById("context-specialty").innerText =
            "Specialty: " + (formData.get("specialty") || "-");

        document.getElementById("context-condition").innerText =
            "Condition: " + (formData.get("core_condition") || "-");

        document.getElementById("context-presentation").innerText =
            "Presentation: " + (formData.get("presentation") || "-");

        document.getElementById("context-learning").innerText =
            "Learning outcome: " + (formData.get("learning_outcome") || "-");

        document.getElementById("context-num").innerText =
            "Questions requested: " + (formData.get("num_questions") || "-");

        progress.innerHTML = `<p>Preparing workspace...</p>`;
        results.innerHTML = `<p>No questions generated yet.</p>`;

        fetch("../app/api/clear_workspace_questions.php", {
            method: "POST",
            body: new URLSearchParams({
                workspace_id: workspaceId
            })
        })
        .then(response => response.text())
        .then(() => {
            progress.innerHTML = `<p>Starting generation job...</p>`;

            return fetch("../app/api/start_generation_job.php", {
                method: "POST",
                body: formData
            });
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                progress.innerHTML = `<p>Generation started. Loading first question...</p>`;
                generateNextQuestion(data.job_id);
            } else {
                progress.innerHTML = `<p>${data.message}</p>`;
            }
        })
        .catch(error => {
            console.error(error);
            progress.innerHTML = `<p>Error starting generation job.</p>`;
        });
    });

    loadExistingQuestions();
});