// Attach event listener
$(document).on('click', '.stomp-btn', function (e) {
    e.preventDefault(); // Prevent default link behavior

    console.log(typeof Swal);

    const itemUuid = $(this).data('item-uuid');
    const itemName = $(this).data('item-name')
    const apiUrl = $(this).data('api-url');
    const deleteAction = $(this).data('delete-action') || false;
    const row = $(this).closest('tr');

    const StompOptions = {
        itemUuid: itemUuid,
        itemName: itemName,
        apiUrl: apiUrl,
        row: row,
        deleteAction: deleteAction,
        title: __('action_confirm'),
        text: __('action_confirm_text'),
        icon: "question",
        responseSuccessTitle: __('stomped'),
        responseSuccessText: __('stomped_success'),
        responseSuccessBtnText: __('close'),
        responseErrorTitle: __('action_error_title'),
        responseErrorText: __('action_error_text'),
        cancelConfirmTitle: __('action_cancel_confirm_title'),
        cancelConfirmText: __('action_cancel_confirm_text'),
        cancelConfirmBtnText: __('close'),
    };

    // Make the POST request to delete the device
    $.post(apiUrl, {
        [itemName]: itemUuid,
        "X-HTTP-Method-Override": "POST"
    })

        .done(function (response) {
            // Parse the response if necessary
            Swal.fire({
                background: background,
                color: color,
                title: StompOptions.responseSuccessTitle || "Added!",
                text: response.message || StompOptions.responseSuccessText || "Your stomp has been added.",
                confirmButtonText: StompOptions.responseSuccessBtnText,
                icon: "success",
                customClass: {
                    confirmButton: "btn btn-success",
                },
                buttonsStyling: true,
            }).then(() => {
                const counterEl = $("#count-" + itemUuid);

                if (counterEl.length) {
                    const currentCount = parseInt(counterEl.text(), 10);
                    if (!isNaN(currentCount)) {
                        counterEl.text(currentCount + 1);
                    }
                }
            });
        })
        .fail(function (jqXHR) {
            let response = jqXHR.responseJSON || {};

            Swal.fire({
                background: background,
                color: color,
                title: StompOptions.responseErrorTitle,
                text: response.message || StompOptions.responseErrorText,
                icon: "error",
                customClass: {confirmButton: "btn btn-danger"},
                buttonsStyling: false,
            });
        });
});

// Attach event listener
$(document).on('click', '.stomp-delete-btn', function (e) {
    e.preventDefault(); // Prevent default link behavior

    const row = $(this).closest('tr');

    const deleteStompOptions = {
        itemUuid: $(this).data('item-uuid'),
        itemName: $(this).data('item-name'),
        apiUrl: $(this).data('api-url'),
        row: row,
        deleteAction: $(this).data('delete-action') || false,
        title: __('action_confirm'),
        text: __('action_confirm_text'),
        confirmButtonText: __('action_confirm_button'),
        cancelButtonText: __('action_cancel_button'),
        responseSuccessTitle: __('deleted'),
        responseSuccessText: __('action_success_text'),
        responseSuccessBtnText: __('close'),
        responseErrorTitle: __('action_error_title'),
        responseErrorText: __('action_error_text'),
        cancelConfirmBtnText: __('close'),
    };

    // Make the POST request to delete the device
    $.post(deleteStompOptions.apiUrl, {
        [deleteStompOptions.itemName]: deleteStompOptions.itemUuid,
        "X-HTTP-Method-Override": "DELETE"
    })

        .done(function (response) {
            // Parse the response if necessary
            Swal.fire({
                background: background,
                color: color,
                title: deleteStompOptions.responseSuccessTitle || "Deleted!",
                text: response.message || deleteStompOptions.responseSuccessText || "Your item has been deleted.",
                confirmButtonText: deleteStompOptions.responseSuccessBtnText,
                icon: "error",
                customClass: {
                    confirmButton: "btn btn-danger",
                },
                buttonsStyling: true,
            }).then(() => {
                // If deleteAction is false, remove the row; otherwise, process show and hide actions
                const userUUID = deleteStompOptions.row.data('user-uuid');
                const counterEl = $("#count-" + userUUID);

                if (counterEl.length) {
                    const currentCount = parseInt(counterEl.text(), 10);
                    if (!isNaN(currentCount) && currentCount > 0) {
                        counterEl.text(currentCount - 1);
                    }
                }

                if (!deleteStompOptions.deleteAction || deleteStompOptions.deleteAction === "false") {
                    row.fadeOut(500, function () {
                        $(this).remove();
                    });
                }
            });
        })
        .fail(function (jqXHR) {
            let response = jqXHR.responseJSON || {};

            Swal.fire({
                background: background,
                color: color,
                title: deleteStompOptions.responseErrorTitle,
                text: response.message || deleteStompOptions.responseErrorText,
                icon: "error",
                customClass: {confirmButton: "btn btn-danger"},
                buttonsStyling: false,
            });
        });
});

const gruvboxColors = [
    "#fabd2f", // yellow
    "#b8bb26", // green
    "#fb4934", // red
    "#8ec07c", // aqua
    "#83a598", // blue
    "#fe8019", // orange
];

const assignedColors = {};
const usedColors = new Set();

function hexToRGBA(hex, alpha) {
    hex = hex.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    return `rgba(${r},${g},${b},${alpha})`;
}

function getColorForUser(name) {
    if (assignedColors[name]) return assignedColors[name];

    let hash = 0;
    for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    let preferredIndex = Math.abs(hash) % gruvboxColors.length;
    let preferredColor = gruvboxColors[preferredIndex];

    if (!usedColors.has(preferredColor)) {
        assignedColors[name] = preferredColor;
        usedColors.add(preferredColor);
        return preferredColor;
    }

    const unused = gruvboxColors.filter(c => !usedColors.has(c));
    let finalColor = unused.length > 0
        ? unused[Math.floor(Math.random() * unused.length)]
        : gruvboxColors[Math.floor(Math.random() * gruvboxColors.length)];

    assignedColors[name] = finalColor;
    usedColors.add(finalColor);
    return finalColor;
}

let stompChart = null;

// Convert dd/mm/yyyy → Date safely
function parseInputDate(value) {
    if (!value) return null;

    const parts = value.split("/");

    if (parts.length !== 3) return null;

    return new Date(`${parts[2]}-${parts[1]}-${parts[0]}`);
}

// Generate date range (expects existing helper)
function getDatesBetween(startDate, endDate) {
    const dates = [];
    const current = new Date(startDate);

    while (current <= endDate) {
        dates.push(current.toISOString().slice(0, 10));
        current.setDate(current.getDate() + 1);
    }

    return dates;
}

async function loadChart() {
    try {
        // Read inputs safely
        const fromDate = parseInputDate(document.getElementById("fd").value);
        const toDate = parseInputDate(document.getElementById("td").value);

        if (!fromDate || !toDate) {
            console.warn("Invalid date range");
            return;
        }

        const sortedDates = getDatesBetween(fromDate, toDate);

        // Fetch data
        const res = await fetch('/api/v1/office/stompjes/?frontend=1');

        if (!res.ok) {
            console.error(`HTTP ${res.status}`);
            return;
        }

        const data = await res.json();
        const stompData = data.success || [];

        // Build user dataset
        const users = {};

        stompData.forEach(item => {
            const user = item.user_first_name;

            const date = new Date(item.stomp_timestamp * 1000)
                .toISOString()
                .slice(0, 10);

            if (!users[user]) users[user] = {};
            if (!users[user][date]) users[user][date] = 0;

            users[user][date] += 1;
        });

        // Fill missing dates with 0
        Object.keys(users).forEach(user => {
            sortedDates.forEach(date => {
                if (!users[user][date]) {
                    users[user][date] = 0;
                }
            });
        });

        // Build datasets
        const datasets = Object.keys(users).map(user => {
            const color = getColorForUser(user);

            return {
                label: user,
                data: sortedDates.map(date => users[user][date]),
                borderColor: color,
                backgroundColor: hexToRGBA(color, 0.1),
                tension: 0.3
            };
        });

        // Chart config (Chart.js 4.5.1)
        const config = {
            type: 'line',
            data: {
                labels: sortedDates,
                datasets: datasets
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top'
                    },
                    title: {
                        display: true,
                        text: 'Stomps per User per Day'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        };

        // Render / replace chart safely
        const ctx = document.getElementById('stompjesChart');

        if (stompChart instanceof Chart) {
            stompChart.destroy();
        }

        stompChart = new Chart(ctx, config);

    } catch (err) {
        console.error('Failed to load stomp data:', err);
    }
}

$(document).ready(function () {
    $("#datePicker").on("click", function () {
        const fd = $("#fd").val();
        const td = $("#td").val();

        const params = new URLSearchParams(window.location.search);

        if (fd) params.set("fd", fd);
        else params.delete("fd");

        if (td) params.set("td", td);
        else params.delete("td");

        window.location.href = window.location.pathname + "?" + params.toString();
    });

    // Initial chart load
    loadChart();
});