import { Grid } from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js";
import GlobalConfig, { addThousandSeparators } from "../global-config.js";
import moment from "moment";
import InitDatePicker from "../utils/InitDatePicker.js";

class PaymentRecaps {
    constructor() {
        this.toastMessage = document.getElementById("toast-message");
        this.toastElement = document.getElementById("toastNotification");
        this.toast = new bootstrap.Toast(this.toastElement);
        this.table = null;
        this.initTablePaymentRecaps();
        this.initFilterDatepicker();
    }
    initFilterDatepicker() {
        new InitDatePicker(
            "#datepicker-payment-recap",
            this.handleChangeFilterDate.bind(this)
        ).init();
    }
    handleChangeFilterDate(strDate) {
        console.log("filter date : ", strDate);
    }
    formatCategory(category) {
        const categoryMap = {
            potention_sum: "Potensi",
            non_verified_sum: "Belum Terverifikasi",
            verified_sum: "Terverifikasi",
            business_sum: "Usaha",
            non_business_sum: "Non Usaha",
            spatial_sum: "Tata Ruang",
            waiting_click_dpmptsp_sum: "Menunggu Klik DPMPTSP",
            issuance_realization_pbg_sum: "Realisasi Terbit PBG",
            process_in_technical_office_sum: "Proses Di Dinas Teknis",
        };

        return categoryMap[category] || category; // Return mapped value or original category
    }
    initTablePaymentRecaps() {
        let tableContainer = document.getElementById("table-payment-recaps");

        this.table = new Grid({
            columns: [
                { name: "Kategori", data: (row) => row[0] },
                { name: "Nominal", data: (row) => row[1] },
                {
                    name: "Created",
                    data: (row) => row[2],
                    attributes: { style: "width: 200px; white-space: nowrap;" },
                },
            ],
            pagination: {
                limit: 10,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            server: {
                url: `${GlobalConfig.apiHost}/api/payment-recaps`,
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (response) => {
                    console.log("API Response:", response); // Debugging

                    if (!response.data || !Array.isArray(response.data)) {
                        console.error(
                            "Error: Data is not an array",
                            response.data
                        );
                        return [];
                    }

                    return response.data.map((item) => [
                        this.formatCategory(item.category ?? "Unknown"), // Ensure category is not null
                        addThousandSeparators(
                            Number(item.nominal).toString() || 0
                        ), // Ensure nominal is a valid number
                        moment(item.created_at).isValid()
                            ? moment(item.created_at).format(
                                  "YYYY-MM-DD H:mm:ss"
                              )
                            : "-", // Handle invalid dates
                    ]);
                },
                total: (response) => response.pagination?.total || 0,
            },
            width: "auto",
            fixedHeader: true,
        }).render(tableContainer);
    }
}
document.addEventListener("DOMContentLoaded", function (e) {
    new PaymentRecaps();
});
