import('bootstrap');
import $ from 'jquery';
import Chart from 'chart.js/auto';
import * as bootstrap from 'bootstrap';
import { initRegistrationTable } from './registration';
import { initLoginTable } from './login';
import { initTrialVersionTable } from './trialversion';
import { initLicenseTable } from './license';

type OffcanvasInitKey = 'registration' | 'login' | 'trialversion' | 'license';

const offcanvasInitMap: Record<OffcanvasInitKey, () => void> = {
    registration: initRegistrationTable,
    login: initLoginTable,
    trialversion: initTrialVersionTable,
    license: initLicenseTable,
};

function destroyOffcanvasTables(): void {
    ['#registrationTable', '#loginTable', '#trialVersionTable', '#licenseTable'].forEach((selector) => {
        if ($.fn.DataTable.isDataTable(selector)) {
            $(selector).DataTable().destroy();
        }
    });
}

$(function () {
    const unused_space: number = $('#unused_space').val() as number;
    const used_space: number = $('#used_space').val() as number;
    const used_space_formatted: number = $('#used_space_formatted').val() as number;
    const unused_space_formatted: number = $('#unused_space_formatted').val() as number;

    const used_space_other: number = $('#used_space_other').val() as number;
    const used_space_storage: number = $('#used_space_storage').val() as number;
    const used_space_storage_formatted: number = $('#used_space_storage_formatted').val() as number;
    const used_space_other_formatted: number = $('#used_space_other_formatted').val() as number;

    const pieChart = document.getElementById('pie-chart') as HTMLCanvasElement | null;
    if (pieChart) {
        new Chart(pieChart, {
            type: 'pie',
            data: {
                labels: ['frei: ' + unused_space_formatted, 'System: ' + used_space_other_formatted, 'Storage: ' + used_space_storage_formatted],
                datasets: [{
                    label: 'Festplattennutzung',
                    backgroundColor: ['#fcfcfd', '#003f6a', '#3f81b6'],
                    data: [
                        unused_space, used_space_other, used_space_storage,
                    ],
                }],
            },
        });
    }

    const pieChartStorage = document.getElementById('pie-chart-storage') as HTMLCanvasElement | null;
    if (pieChartStorage) {
        new Chart(pieChartStorage, {
            type: 'pie',
            data: {
                labels: ['System: ' + used_space_other_formatted, 'Storage: ' + used_space_storage_formatted],
                datasets: [{
                    label: 'Verhältnis System / Storage',
                    backgroundColor: ['#003f6a', '#3f81b6'],
                    data: [
                        used_space_other, used_space_storage,
                    ],
                }],
            },
        });
    }

    const offcanvasEl = document.getElementById('admDashboardOffcanvas');
    const offcanvasTitle = document.getElementById('admDashboardOffcanvasLabel');
    const offcanvasContent = document.getElementById('admDashboardOffcanvasContent');

    if (!offcanvasEl || !offcanvasTitle || !offcanvasContent) {
        return;
    }

    // Move the dashboard offcanvas to <body> so it is not trapped
    // inside lower z-index stacking contexts of page containers.
    if (offcanvasEl.parentElement !== document.body) {
        document.body.appendChild(offcanvasEl);
    }

    const offcanvas = new bootstrap.Offcanvas(offcanvasEl);
    const triggers = document.querySelectorAll<HTMLAnchorElement>('.js-adm-dashboard-offcanvas-link');

    triggers.forEach((trigger) => {
        trigger.addEventListener('click', async (event) => {
            event.preventDefault();

            const url = trigger.getAttribute('href');
            if (!url) {
                return;
            }

            const initKey = trigger.dataset.offcanvasInit as OffcanvasInitKey | undefined;
            offcanvasTitle.textContent = trigger.dataset.offcanvasTitle || 'Details';

            const resolvedUrl = new URL(url, window.location.origin);
            resolvedUrl.searchParams.set('partial', '1');

            offcanvasContent.innerHTML = '<div class="p-4 text-muted">Lade …</div>';
            offcanvas.show();

            try {
                const response = await fetch(resolvedUrl.toString(), {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });

                if (!response.ok) {
                    throw new Error('HTTP ' + response.status);
                }

                destroyOffcanvasTables();
                offcanvasContent.innerHTML = await response.text();

                if (initKey && offcanvasInitMap[initKey]) {
                    offcanvasInitMap[initKey]();
                }
            } catch (error) {
                offcanvasContent.innerHTML = '<div class="p-4 text-danger">Inhalt konnte nicht geladen werden.</div>';
                console.error('Offcanvas load failed:', error);
            }
        });
    });

    offcanvasEl.addEventListener('hidden.bs.offcanvas', () => {
        destroyOffcanvasTables();
        offcanvasContent.innerHTML = '';
    });
});
