$(document).ready(function () {

    // Initialize Select2 for custom numbers
    $(".select2-tags").select2({
        tags: true,
        tokenSeparators: [",", " "],
        width: "100%",
        placeholder: "Type numbers and press Enter..."
    });

    // Load existing numbers into Modal
    function loadContacts(selectedContacts = []) {
        // Destroy existing DataTable if it exists
        if ($.fn.DataTable.isDataTable('#contactsTable')) {
            $('#contactsTable').DataTable().destroy();
        }

        $("#contactsTable tbody").html('<tr><td colspan="3" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</td></tr>');

        $.post("../api/group_actions.php", { action: "fetch_available_numbers" }, function (res) {
            if (res.status === "success") {
                let html = "";
                if (res.data.length === 0) {
                    html = '<tr><td colspan="3" class="text-center text-muted">No numbers found in SMS history.</td></tr>';
                } else {
                    // Chunk data into groups of 3
                    const chunkSize = 3;
                    for (let i = 0; i < res.data.length; i += chunkSize) {
                        const chunk = res.data.slice(i, i + chunkSize);
                        html += '<tr>';

                        // Create 3 cells
                        for (let j = 0; j < chunkSize; j++) {
                            if (j < chunk.length) {
                                let item = chunk[j];
                                let isChecked = selectedContacts.includes(item.phone) ? "checked" : "";
                                let pills = "";
                                if (item.pills && item.pills.length > 0) {
                                    item.pills.forEach(p => {
                                        pills += `<span class="badge bg-secondary ms-1" style="font-size: 0.7em;">${p}</span>`;
                                    });
                                }

                                html += `
                                <td class="align-middle p-2">
                                    <div class="d-flex align-items-center" style="gap: 3px;">
                                        <input class="form-check-input contact-check m-0" type="checkbox" name="contacts[]" value="${item.phone}" id="check_${item.phone}" ${isChecked} style="cursor: pointer;">
                                        <label class="cursor-pointer mb-0 fw-bold text-truncate mx-4" for="check_${item.phone}" style="max-width: 140px;">${item.phone}</label>
                                        <div class="d-flex flex-wrap gap-1">${pills}</div>
                                    </div>
                                </td>`;
                            } else {
                                // Empty cell to maintain structure
                                html += '<td></td>';
                            }
                        }
                        html += '</tr>';
                    }
                }
                $("#contactsTable tbody").html(html);

                // Initialize DataTable
                $('#contactsTable').DataTable({
                    "pageLength": 5, // 5 rows * 3 cols = 15 items per page
                    "lengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]],
                    "ordering": false, // Disable ordering as it breaks the grid structure logic
                    "language": {
                        "searchPlaceholder": "Search phone...",
                        "sSearch": ""
                    },
                    "columnDefs": [
                        { "width": "33.33%", "targets": [0, 1, 2] } // Equal width columns
                    ]
                });
            }
        }, "json");
    }

    $("#btnNewGroup").click(function () {
        $("#modalTitle").text("Create New Group");
        $("#groupAction").val("create_group");
        $("#groupId").val("");
        $("#groupName").val("");
        $("#customNumbers").val(null).trigger("change"); // Clear Select2
        loadContacts([]);
        $("#groupModal").modal("show");
    });

    // Edit Group
    $(".btn-edit").click(function () {
        let tr = $(this).closest("tr");
        let id = tr.data("id");
        let name = tr.find(".group-name").text();

        $("#modalTitle").text("Edit Group");
        $("#groupAction").val("update_group");
        $("#groupId").val(id);
        $("#groupName").val(name);

        // Fetch current members and available numbers
        Promise.all([
            $.post("../api/group_actions.php", { action: "fetch_group_members", group_id: id }),
            $.post("../api/group_actions.php", { action: "fetch_available_numbers" })
        ]).then(function (results) {
            let groupMembers = results[0].data; // Array of phone numbers in this group
            let availableNumbers = results[1].data; // Array of {phone, pills} from SMS history

            // Get list of available contact phone numbers
            let availablePhones = availableNumbers.map(item => item.phone);

            // Separate: numbers that exist in contact list vs custom numbers
            let checkboxNumbers = groupMembers.filter(num => availablePhones.includes(num));
            let customNumbers = groupMembers.filter(num => !availablePhones.includes(num));

            // Load checkboxes
            loadContacts(checkboxNumbers);

            // Pre-populate Select2 with custom numbers
            $("#customNumbers").empty(); // Clear existing
            customNumbers.forEach(function (num) {
                let option = new Option(num, num, true, true);
                $("#customNumbers").append(option);
            });
            $("#customNumbers").trigger("change"); // Refresh Select2

            $("#groupModal").modal("show");
        }).catch(function (error) {
            console.error("Failed to load group data:", error);
            alert("Failed to load group data");
        });
    });

    // Save Group
    $("#btnSaveGroup").click(function () {
        let formData = $("#groupForm").serialize();

        $.post("../api/group_actions.php", formData, function (res) {
            if (res.status === "success") {
                location.reload();
            } else {
                alert(res.message);
            }
        }, "json").fail(function (xhr, status, error) {
            alert("Failed to save group. Check console for details.");
        });
    });

    // Status Toggle
    $(".btn-status-toggle").click(function () {
        let tr = $(this).closest("tr");
        let id = tr.data("id");

        // Button text shows what action to take: "Active" means make it active, "Inactive" means make it inactive
        let buttonText = $(this).text().trim();
        let newStatus = buttonText.includes("Active") ? "active" : "inactive";

        $.post("../api/group_actions.php", { action: "toggle_status", group_id: id, status: newStatus }, function (res) {
            if (res.status === "success") {
                location.reload();
            } else {
                alert(res.message || "Failed to update status");
            }
        }, "json");
    });

    // Inject Custom Styles safely
    $("head").append("<style>" +
        ".badge.bg-blue { background-color: #206bc4 !important; color: #fff; }" +
        ".badge.bg-azure { background-color: #45aaf2 !important; color: #fff; }" +
        ".badge.bg-indigo { background-color: #6574cd !important; color: #fff; }" +
        ".badge.bg-purple { background-color: #a55eea !important; color: #fff; }" +
        ".badge.bg-pink { background-color: #f66d9b !important; color: #fff; }" +
        ".badge.bg-red { background-color: #cd201f !important; color: #fff; }" +
        ".badge.bg-orange { background-color: #fd9644 !important; color: #fff; }" +
        ".badge.bg-yellow { background-color: #f1c40f !important; color: #fff; }" +
        ".badge.bg-lime { background-color: #7bd235 !important; color: #fff; }" +
        ".badge.bg-green { background-color: #5eba00 !important; color: #fff; }" +
        ".badge.bg-teal { background-color: #2bcbba !important; color: #fff; }" +
        ".badge.bg-cyan { background-color: #17a2b8 !important; color: #fff; }" +
        ".badge.bg-gray { background-color: #a8aeb7 !important; color: #fff; }" +
        ".badge.bg-gray-dark { background-color: #545d6d !important; color: #fff; }" +
        ".delete-member { transition: transform 0.2s; }" +
        ".delete-member:hover { transform: scale(1.1); opacity: 1 !important; }" +
        "@media (max-width: 768px) { #contactsTable tbody tr { display: flex; flex-wrap: wrap; } #contactsTable tbody td { width: 100% !important; display: block; box-sizing: border-box; } #contactsTable thead { display: none; } }" +
        "</style>");

    // View Contacts
    $(".btn-view").click(function () {
        let tr = $(this).closest("tr");
        let id = tr.data("id");
        $("#viewContactList").html(`<div class="text-center w-100"><i class="fa fa-spinner fa-spin"></i> Loading...</div>`);
        $("#viewContactsModal").modal("show");

        // Save group ID for delete action
        $("#viewContactsModal").data("group-id", id);

        $.post("../api/group_actions.php", { action: "fetch_group_members", group_id: id }, function (res) {
            // Colors matching the user provided "Color tag" image
            const colors = [
                "blue", "azure", "indigo", "purple", "pink", "red",
                "orange", "yellow", "lime", "green", "teal", "cyan",
                "gray", "gray-dark"
            ];

            let html = "";
            if (res.data && res.data.length > 0) {
                res.data.forEach((num, index) => {
                    let colorClass = colors[index % colors.length];
                    html += `
                    <span class="badge bg-${colorClass} fs-6 py-2 px-3 d-inline-flex align-items-center gap-2">
                        ${num}
                        <i class="fa fa-times text-danger delete-member cursor-pointer ms-2" 
                           data-phone="${num}" 
                           title="Remove" 
                           style="cursor: pointer; font-size: 14px; background: white; border-radius: 50%; padding: 2px 4px; height: 18px; width: 18px; display: flex; align-items: center; justify-content: center; opacity: 0.8;"></i>
                    </span>`;
                });
            } else {
                html = `<p class="text-muted">No contacts in this group</p>`;
            }
            $("#viewContactList").html(html);
        }, "json");
    });

    // Delete Member Handler
    $(document).on("click", ".delete-member", function () {
        let phone = $(this).data("phone");
        let groupId = $("#viewContactsModal").data("group-id");
        let badge = $(this).closest(".badge"); // Ensure we target the badge 

        if (confirm("Are you sure you want to remove " + phone + " from this group?")) {
            $.post("../api/group_actions.php", { action: "remove_member", group_id: groupId, phone: phone }, function (res) {
                if (res.status === "success") {
                    // Animate and remove
                    badge.fadeOut(300, function () { $(this).remove(); });
                } else {
                    alert(res.message);
                }
            }, "json");
        }
    });

    // Delete Group Handler
    $(".btn-delete").click(function () {
        if (!confirm("Are you sure?")) return;
        let id = $(this).closest("tr").data("id");
        $.post("../api/group_actions.php", { action: "delete_group", group_id: id }, function (res) {
            location.reload();
        }, "json");
    });

});
