import { Grid } from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js";
import GlobalConfig from "../global-config";
import { Dropzone } from "dropzone";
Dropzone.autoDiscover = false;

class PbgTasks {
    init() {
        this.initTableRequestAssignment();
        this.handleSendNotification();
        this.handleUpload();
        this.handleUploadBeritaAcara();
    }

    initTableRequestAssignment() {
        let tableContainer = document.getElementById("table-pbg-tasks");

        // Pastikan kontainer kosong sebelum merender ulang Grid.js
        tableContainer.innerHTML = "";
        let canUpdate = tableContainer.getAttribute("data-updater") === "1";
        new Grid({
            columns: [
                "ID",
                { name: "Name", width: "15%" },
                { name: "Condition", width: "7%" },
                "Registration Number",
                "Document Number",
                { name: "Address", width: "30%" },
                "Status",
                "Function Type",
                "Consultation Type",
                { name: "Due Date", width: "10%" },
                {
                    name: "Action",
                    formatter: (cell) => {
                        let tableContainer =
                            document.getElementById("table-pbg-tasks");
                        let canUpdate =
                            tableContainer.getAttribute("data-updater") === "1";

                        if (!canUpdate) {
                            return gridjs.html(
                                `<span class="text-muted">No Privilege</span>`
                            );
                        }

                        return gridjs.html(`
                            <div class="d-flex justify-content-center align-items-center gap-2">
                                <a href="/pbg-task/${cell}" class="btn btn-yellow btn-sm d-inline-flex align-items-center justify-content-center">
                                    Detail
                                </a>
                                <button class="btn btn-sm btn-info upload-btn" data-id="${cell}">
                                    Upload Bukti Bayar
                                </button>
                                <button class="btn btn-sm btn-info upload-btn-berita-acara" data-id="${cell}">
                                    Buat Berita Acara
                                </button>
                            </div>
                        `);
                    },
                },
            ],
            search: {
                server: {
                    url: (prev, keyword) => `${prev}?search=${keyword}`,
                },
                debounceTimeout: 1000,
            },
            pagination: {
                limit: 15,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            server: {
                url: `${GlobalConfig.apiHost}/api/request-assignments`,
                credentials: "include",
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (data) =>
                    data.data.map((item) => [
                        item.id,
                        item.name,
                        item.condition,
                        item.registration_number,
                        item.document_number,
                        item.address,
                        item.status_name,
                        item.function_type,
                        item.consultation_type,
                        item.due_date,
                        item.id,
                    ]),
                total: (data) => data.meta.total,
            },
        }).render(document.getElementById("table-pbg-tasks"));
    }

    handleSendNotification() {
        this.toastMessage = document.getElementById("toast-message");
        this.toastElement = document.getElementById("toastNotification");
        this.toast = new bootstrap.Toast(this.toastElement);

        document
            .getElementById("sendNotificationBtn")
            .addEventListener("click", () => {
                let notificationStatus =
                    document.getElementById("notificationStatus").value;

                // Show success toast
                this.toastMessage.innerText = "Notifikasi berhasil dikirim!";
                this.toast.show();

                // Close modal after sending
                let modal = bootstrap.Modal.getInstance(
                    document.getElementById("sendNotificationModal")
                );
                modal.hide();
            });
    }

    handleUpload() {
        // Handle button click to show modal
        document.addEventListener("click", function (event) {
            if (event.target.classList.contains("upload-btn")) {
                // Show modal
                let uploadModal = new bootstrap.Modal(
                    document.getElementById("uploadModal")
                );
                uploadModal.show();
            }
        });
        let dropzone = new Dropzone("#singleFileDropzone", {
            url: "/upload-bukti-bayar", // Adjust to your backend endpoint
            maxFiles: 1, // Allow only 1 file
            maxFilesize: 5, // Limit size to 5MB
            acceptedFiles: ".jpg,.png,.pdf", // Allowed file types
            autoProcessQueue: false, // Prevent automatic upload
            addRemoveLinks: true, // Show remove button
            dictDefaultMessage: "Drop your file here or click to upload.",
            init: function () {
                let dz = this;

                // Remove previous file when a new file is added
                dz.on("addedfile", function () {
                    if (dz.files.length > 1) {
                        dz.removeFile(dz.files[0]);
                    }
                });

                // Handle upload button click
                document
                    .getElementById("uploadBtn")
                    .addEventListener("click", function () {
                        if (dz.getQueuedFiles().length > 0) {
                            dz.processQueue(); // Manually process upload
                        } else {
                            alert("Please select a file to upload.");
                        }
                    });

                // Success callback
                dz.on("success", function (file, response) {
                    alert("File uploaded successfully!");
                    dz.removeAllFiles(); // Clear after upload
                });

                // Error callback
                dz.on("error", function (file, errorMessage) {
                    alert("Upload failed: " + errorMessage);
                });
            },
        });
    }

    handleUploadBeritaAcara() {
        // Handle button click to show modal
        document.addEventListener("click", function (event) {
            if (event.target.classList.contains("upload-btn-berita-acara")) {
                // Show modal
                let uploadModal = new bootstrap.Modal(
                    document.getElementById("uploadBeritaAcara")
                );
                uploadModal.show();
            }
        });
    }
}

document.addEventListener("DOMContentLoaded", function (e) {
    new PbgTasks().init();
});
