$(document).ready(function() {
    let currentPage = 1;
    let charts = {};

    const now = new Date();
    const localToday = now.toLocaleDateString('en-CA');
    const localFirstDay = new Date(now.getFullYear(), now.getMonth(), 2).toLocaleDateString('en-CA').substring(0, 8) + '01';

    $('#startDate').val(localFirstDay);
    $('#endDate').val(localToday);

    let table = $('#empTable').DataTable({
        dom:'t',
        processing: true,
        serverSide: true,
        searching: false,
        lengthChange: false,
        ordering: false,
        info: false,
        ajax: {
            url: url,
            type: "GET",
            data: function (d) {
                d.startDate = $('#startDate').val();
                d.endDate = $('#endDate').val();


            },
            dataFilter: function(data){
                let json = JSON.parse(data);
                json.draw = json.pagination.draw;
                json.recordsTotal = json.pagination.recordsTotal;
                json.recordsFiltered = json.pagination.recordsFiltered;
                return JSON.stringify(json);
            },
            dataSrc: function (json) {
                return json.pagination.data;
            }
        },
        pageLength: $('#dLength').val(),
        columns: [
            {
                data: 'type_report',
                orderable: false,
                render: function(data, type, row) {
                    if (data === 1) {
                        return `
                <div class="fw-bold">Pelanggaran SOP</div>
                <small class="text-muted">Kepatuhan Prosedur</small>
            `;
                    } else if (data === 2) {
                        let detailInsiden = row.title_medical ? row.title_medical.name : '';
                        return `
                <div class="fw-bold">Insiden Keselamatan Petugas</div>
                <div class="badge bg-danger-subtle text-danger p-1" style="font-size: 0.75rem;">
                    <i class="bi bi-info-circle me-1"></i>${detailInsiden}
                </div>
            `;
                    } else if (data === 3) {
                        const haisMap = {
                            1: 'HAP',
                            2: 'VAP',
                            3: 'SSI',
                            4: 'IADP',
                            5: 'CAUTI'
                        };

                        let namaHais = haisMap[row.type_hais] || 'Lainnya';

                        return `
                <div class="fw-bold">Kejadian HAIS</div>
                <div class="badge bg-warning-subtle text-warning p-1" style="font-size: 0.75rem;">
                    <i class="bi bi-virus me-1"></i>${namaHais}
                </div>
            `;
                    }
                    return '';
                }
            },
            {
                data: 'report_roles',
                name: 'report_roles.role.name',
                render: function (data, type, row) {
                    if (data && Array.isArray(data) && data.length > 0) {
                        return data.map(function(item) {
                            return item.role ? item.role.name : '';
                        }).filter(name => name !== '').join(', ');
                    }
                    return '-';
                }
            },
            {
                data: 'status',
                orderable: false,
                render: function(data) {
                    if(data === 1) {
                        return `<span class="status-new">Baru</span>`;
                    } else if (data === 3) {
                        return `<span class="status-process">Diproses</span>`;
                    } else if (data === 2) {
                        return `<span class="status-verification">Verifikasi</span>`;
                    } else {
                        return `<span class="status-finish">Selesai</span>`;
                    }
                }
            },
            {data: 'created_at_local'},
            {
                data: 'id',
                orderable: false,
                render: function(id) {
                    return `
        <div class="dropdown text-center">
            <button class="btn btn-sm action-btn action-btn-sm border-0 bg-transparent"
                    data-coreui-toggle="dropdown"
                    aria-expanded="false">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16">
                    <circle cx="256" cy="53.333" r="53.333"/>
                    <circle cx="256" cy="256" r="53.333"/>
                    <circle cx="256" cy="458.667" r="53.333"/>
                </svg>
            </button>

            <div class="dropdown-menu dropdown-menu-end shadow-sm">
                <a class="dropdown-item small" href="/report/detail/${id}" target="_blank" rel="noopener noreferrer">
                    <i class="bi bi-pencil-square me-2"></i> Detail
                </a>


            </div>
        </div>
    `;
                }
            }
        ],
        columnDefs: [
            { targets: 3, className: 'text-start'},
            { targets: 4, className: 'text-center' ,width: "110px"}
        ],
    });
    table.on('xhr', function(e, settings, json) {
        if (!json) return;

        loadDashboard(json);
        $('#start').text(json.pagination.pagination.from ?? 0);
        $('#end').text(json.pagination.pagination.to ?? 0);
        $('#total').text(json.pagination.pagination.total ?? 0);

        totalPage = json.pagination.data.last_page;

        let pagination = $('#custom-pagination');
        pagination.empty();

        let prevClass = json.pagination.pagination.current_page == 1 ? 'disabled' : '';
        pagination.append(`<li class="page-item ${prevClass}">
        <a class="page-link" href="#" data-page="prev">Previous</a>
    </li>`);

        for (let i = 1; i <= json.pagination.pagination.last_page; i++) {
            let activeClass = json.pagination.pagination.current_page == i ? 'active' : '';
            pagination.append(`<li class="page-item ${activeClass}">
            <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>`);
        }

        let nextClass = json.pagination.pagination.current_page == json.pagination.data.last_page ? 'disabled' : '';
        pagination.append(`<li class="page-item ${nextClass}">
        <a class="page-link" href="#" data-page="next">Next</a>
    </li>`);
    });
    $(document).on('click', '#custom-pagination a', function(e) {
        e.preventDefault();
        let page = $(this).data('page');

        if (page === 'prev' && currentPage > 1) currentPage--;
        else if (page === 'next' && currentPage < totalPage) currentPage++;
        else if (!isNaN(page)) currentPage = parseInt(page);
        else return;

        table.ajax.reload(null, false);
    });

    $('#applyBtn').on('click', function() {
        const btn = $(this);

        const originalContent = btn.html();

        btn.html('<img src="/assets/custom/images/loading.gif" width="20" class="me-2"> Mohon Tunggu...');
        btn.prop('disabled', true);

        currentPage = 1;
        table.ajax.reload(function() {
            btn.html(originalContent);
            btn.prop('disabled', false);
        });
    });

    function loadDashboard(res) {

        $('#totalPelanggaranV').text(res.totalReport);
        $('#sopV').text(res.totalReportSOP);
        $('#kV').text(res.totalReportK);
        $('#insidenV').text(res.totalReportI);

        renderLineChart('trendLineChart', res.trendTypeReportChart.datasets, res.trendTypeReportChart.labels);
        renderPieChart('trendTitleMedical', res.titleTrendChart);
        renderBarChart('trendLocation', res.locationTrendChart);
        renderDonutChart('responseTimeChart', res.effectivenessChart, res.averageResponseTime);

    }

    function renderLineChart(id, datasets, labels) {
        if (charts[id]) charts[id].destroy();
        const ctx = document.getElementById(id).getContext('2d');
        charts[id] = new Chart(ctx, {
            type: 'line',
            data: { labels: labels, datasets: datasets },
            options: { responsive: true, maintainAspectRatio: false }
        });
    }

    function renderPieChart(id, chartData) {
        if (charts[id]) charts[id].destroy();
        const ctx = document.getElementById(id).getContext('2d');
        charts[id] = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: chartData.labels,
                datasets: chartData.datasets
            },
            options: {
                responsive: true,
                plugins: { legend: { position: 'right' } }
            }
        });
    }

    function renderBarChart(id, chartData) {
        if (charts[id]) charts[id].destroy();
        const ctx = document.getElementById(id).getContext('2d');
        charts[id] = new Chart(ctx, {
            type: 'bar',
            data: chartData,
            options: { indexAxis: 'y', responsive: true }
        });
    }

    function renderDonutChart(id, chartData, avgTime) {
        if (charts[id]) charts[id].destroy();
        const ctx = document.getElementById(id).getContext('2d');
        charts[id] = new Chart(ctx, {
            type: 'doughnut',
            data: chartData,
            options: {
                plugins: {
                    title: { display: true, text: 'Rata-rata Selesai: ' + avgTime, position: 'bottom' }
                }
            }
        });
    }
});
