"use strict";

const PassCodesPage = (function () {
    const modalElement = document.getElementById("kt_modal_pass_code_qr");
    const qrContainer = document.getElementById("pass_code_qr_container");
    const qrName = document.getElementById("pass_code_qr_name");
    const qrCodeValue = document.getElementById("pass_code_qr_code");
    const qrStatus = document.getElementById("pass_code_qr_status");
    const tableBody = document.getElementById("pass-codes-table-body");
    const listUrl = document.body.dataset.passCodesListUrl;

    let modalInstance = null;
    let qrInstance = null;

    const escapeHtml = (value) => String(value)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");

    const formatDateTime = (isoValue) => {
        if (!isoValue) {
            return "-";
        }

        const date = new Date(isoValue);
        if (Number.isNaN(date.getTime())) {
            return "-";
        }

        return new Intl.DateTimeFormat("es-MX", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
            hour12: false
        }).format(date).replace(",", "");
    };

    const statusBadgeClass = (status) => (
        status === "ACTIVO" ? "badge-light-success" : "badge-light-warning"
    );

    const scannedBadgeClass = (scanned) => (
        scanned ? "badge-light-warning" : "badge-light-primary"
    );

    const renderRows = (passCodes) => {
        if (!tableBody) {
            return;
        }

        if (!passCodes.length) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-gray-500">Aun no hay codigos pase registrados.</td>
                </tr>
            `;
            return;
        }

        tableBody.innerHTML = passCodes.map((passCode) => `
            <tr>
                <td class="fw-semibold text-gray-800">${escapeHtml(passCode.name)}</td>
                <td>
                    <span class="badge badge-light-dark fs-7 fw-bold">${escapeHtml(passCode.code)}</span>
                </td>
                <td>${formatDateTime(passCode.createdAt)}</td>
                <td>
                    <span class="badge fs-7 fw-bold ${statusBadgeClass(passCode.status)}">${escapeHtml(passCode.status)}</span>
                </td>
                <td>
                    <span class="badge fs-7 fw-bold ${scannedBadgeClass(passCode.scanned)}">
                        ${passCode.scanned ? "Si" : "No"}
                    </span>
                </td>
                <td>${formatDateTime(passCode.scannedAt)}</td>
                <td class="text-end">
                    <button type="button"
                            class="btn btn-light-primary btn-sm btn-qr-pass-code"
                            data-code="${escapeHtml(passCode.code)}"
                            data-name="${escapeHtml(passCode.name)}"
                            data-status="${escapeHtml(passCode.status)}">
                        <i class="ki-duotone ki-scan-barcode fs-3">
                            <span class="path1"></span>
                            <span class="path2"></span>
                            <span class="path3"></span>
                            <span class="path4"></span>
                        </i>
                        Ver QR
                    </button>
                </td>
            </tr>
        `).join("");
    };

    const refreshPassCodes = async () => {
        if (!listUrl) {
            return;
        }

        try {
            const response = await fetch(listUrl, {
                headers: {
                    Accept: "application/json"
                }
            });

            if (!response.ok) {
                return;
            }

            const passCodes = await response.json();
            renderRows(passCodes);
        } catch (error) {
            console.error("No fue posible actualizar la lista de codigos pase.", error);
        }
    };

    const clearQr = () => {
        if (qrContainer) {
            qrContainer.innerHTML = "";
        }
        qrInstance = null;
    };

    const openQrModal = (button) => {
        if (!modalElement || typeof QRCode === "undefined") {
            return;
        }

        const code = button.dataset.code;
        const name = button.dataset.name;
        const status = button.dataset.status;

        clearQr();
        qrInstance = new QRCode(qrContainer, {
            text: code,
            width: 240,
            height: 240,
            colorDark: "#181C32",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });

        if (qrName) {
            qrName.textContent = name;
        }
        if (qrCodeValue) {
            qrCodeValue.textContent = code;
        }
        if (qrStatus) {
            qrStatus.textContent = status;
            qrStatus.className = `badge fs-7 fw-bold ${statusBadgeClass(status)}`;
        }

        if (!modalInstance) {
            modalInstance = new bootstrap.Modal(modalElement);
        }

        modalInstance.show();
    };

    const bindEvents = () => {
        document.addEventListener("click", (event) => {
            const button = event.target.closest(".btn-qr-pass-code");
            if (button) {
                openQrModal(button);
            }
        });

        if (modalElement) {
            modalElement.addEventListener("hidden.bs.modal", refreshPassCodes);
        }
    };

    return {
        init: function () {
            bindEvents();
        }
    };
})();

document.addEventListener("DOMContentLoaded", function () {
    PassCodesPage.init();
});