import { fileManagerInitByClass } from "@/shared/js/primary-dashboard/file-manager";
import { select2InitByClass } from "@/shared/js/select2";
import { toastError } from "@/shared/js/toast";
import $ from "jquery";

fileManagerInitByClass("file-uploader", "image");

select2InitByClass();

$("#add_gap_filler").on("click", function () {
    const questionText = $("#question_text").val();

    const matches = questionText.match(/\{([A-Z])\}/g) || [];

    const usedLetters = matches.map((m) => m.replace(/\{|\}/g, ""));
    let nextLetter = null;

    for (let i = 0; i < 26; i++) {
        const letter = String.fromCharCode(65 + i); // A-Z
        if (!usedLetters.includes(letter)) {
            nextLetter = letter;
            break;
        }
    }

    if (nextLetter) {
        const newBlank = `{${nextLetter}}`;
        $("#question_text").val(questionText + " " + newBlank);
    } else {
        alert("Maximum 26 gap fillers allowed (A-Z).");
    }
});

$("#explanation_type").on("change", function () {
    const value = $(this).val();

    $("#question-explanation").children().addClass("hidden");

    $("#question-explanation").find("input, textarea").removeAttr("name");

    $("#" + value).removeClass("hidden");

    $("#" + value)
        .find("input, textarea")
        .attr("name", "question_explanation");
});

$("#question_type").on("change", function () {
    const optionsContainer = $("#options_container");
    optionsContainer.children().remove();
    $("#correct_answers_container").children().remove();
    $("#gap_fillers").addClass("hidden");
    $("#question_text_example").addClass("hidden");
    const questionType = $(this).val();
    switch (questionType) {
        case "multiple_choice":
            break;
        case "single_choice":
            break;
        case "fill_in_the_blank":
            $("#gap_fillers").removeClass("hidden");
            $("#question_text_example").removeClass("hidden");
            break;
        case "true_false":
            optionsContainer.append(
                `<div class="space-y-4 border border-neutral-30 dark:border-neutral-500 p-3 rounded-lg  relative" id="meta-row-1">
                    <div class="input-group">
                        <div class="flex justify-between items-center py-2">
                            <label for="name" class="block mb-2 text-sm">Option - A</label>
                            <button type="button" class="btn btn-success correct_answer" data-id="1">
                                <i class="ph ph-check"></i>
                            </button>
                        </div>
                        <input type="text" class="text-input" readonly id="options-label-1" value="True" name="options[0][label]"
                                placeholder="Enter option" />
                        <input type="hidden" name="options[0][value]" id="options-value-1" value="True">
                        <span class="input-text-error"></span>
                    </div>
                </div>
                <div class="space-y-4 border border-neutral-30 dark:border-neutral-500 p-3 rounded-lg  relative" id="meta-row-2">
                    <div class="input-group">
                        <div class="flex justify-between items-center py-2">
                            <label for="name" class="block mb-2 text-sm">Option - B</label>
                            <button type="button" class="btn btn-success correct_answer" data-id="2">
                                <i class="ph ph-check"></i>
                            </button>
                        </div>
                        <input type="text" class="text-input" readonly id="options-label-2" value="False" name="options[1][label]"
                                placeholder="Enter option" />
                        <input type="hidden" name="options[1][value]" id="options-value-2" value="False">
                        <span class="input-text-error"></span>
                    </div>
                </div>
                `
            );
            break;
        default:
            break;
    }
});

$("#extra_field_container").on("click", function () {
    const row_container = $("#options_container");
    const questionType = $("#question_type").val();

    const uniqueId = Date.now(); // Generate a unique ID for each new row
    const rowCount = row_container.children().length;
    const character = getCharByIndex(rowCount);
    if (questionType == "true_false") {
        if (rowCount > 1) {
            toastError("Only True and False option is allowed");
            return;
        }
    }
    row_container.append(
        `<div class="space-y-4 border border-neutral-30 dark:border-neutral-500 p-3 rounded-lg  relative" id="meta-row-${uniqueId}">
            <div class="input-group">
                <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center py-3 border-b border-gray-200 dark:border-gray-700">
                    <label for="name" class="text-sm font-medium text-gray-700 dark:text-gray-200 mb-2 sm:mb-0">
                        Option - ${character.toUpperCase()}
                    </label>

                    <div class="flex items-center gap-3 text-sm text-gray-600 dark:text-gray-400">
                        <span>Mark as correct answer</span>
                        <button type="button" class="correct_answer p-2 rounded-full hover:bg-green-100 dark:hover:bg-green-900 transition" data-id="${uniqueId}" aria-label="Mark as correct">
                            <i class="ph ph-check text-lg text-green-600 dark:text-green-400"></i>
                        </button>
                    </div>
                </div>
                <input type="text" class="text-input" id="options-label-${uniqueId}" value="" name="options[${rowCount}][label]"
                        placeholder="Enter option" />
                <input type="hidden" name="options[${rowCount}][value]" id="options-value-${uniqueId}" value="${character.toUpperCase()}">
                <span class="input-text-error"></span>
            </div>
            <button type="button" class="text-red-500 mt-2 delete-meta absolute right-0 -top-7" data-id="${uniqueId}">
                <i class="ph ph-trash"></i>
            </button>
        </div>`
    );
});

// Event delegation for dynamically added delete buttons
$(document).on("click", ".delete-meta", function () {
    const id = $(this).data("id");
    $(`#meta-row-${id}`).remove();
});

$(document).on("click", ".correct_answer", function () {
    const id = $(this).data("id");
    const value = $(`#options-value-${id}`).val();
    const label = $(`#options-label-${id}`).val();
    if (!label) {
        toastError("Please enter option");
        return;
    }

    const isAlreadyAdded = $("#correct_answers_container").find(`input[value="${value}"]`).length;
    if (isAlreadyAdded) {
        toastError("Already added");
        return;
    }
    const questionType = $("#question_type").val();
    if (questionType == "true_false") {
        if (value != "True" && value != "False") {
            toastError("Only True and False option is allowed");
            return;
        }
        // only one option is allowed
        if ($("#correct_answers_container").children().length > 0) {
            toastError("Only one option is allowed");
            return;
        }
    }

    if (questionType == "single_choice") {
        if ($("#correct_answers_container").children().length > 0) {
            toastError("Only one option is allowed");
            return;
        }
    }
    const row_container = $("#correct_answers_container");
    const uniqueId = Date.now(); // Generate a unique ID for each new row
    const rowCount = row_container.children().length;
    row_container.append(
        `<div class="flex items-center gap-2" id="meta-row-${uniqueId}">
            <span class="text-sm">${value}</span>
            <input type="hidden" name="correct_answers[${rowCount}]" value="${value}">
            <button type="button" class="text-red-500 mt-2 delete-meta" data-id="${uniqueId}">
                <i class="ph ph-trash"></i>
            </button>
        </div>`
    );
});

function getCharByIndex(index) {
    return String.fromCharCode(97 + index);
}
