document.addEventListener('DOMContentLoaded', function () {
    const modal = new bootstrap.Modal(document.getElementById('equipmentModal'));
    const form = document.getElementById('equipmentForm');
    const saveButton = document.getElementById('saveEquipmentButton');
    const saveButtonHtml = saveButton.innerHTML;

    function clearAssignments() {
        document.querySelectorAll('.unit-assignment').forEach(function (input) {
            input.checked = false;
        });
    }

    function setSaving(isSaving) {
        saveButton.disabled = isSaving;
        saveButton.innerHTML = isSaving
            ? '<span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> Saving...'
            : saveButtonHtml;
    }

    async function getJsonResponse(response) {
        let result;

        try {
            result = await response.json();
        } catch (error) {
            throw new Error('The server returned an invalid response.');
        }

        if (!response.ok) {
            throw new Error(result.message || 'Request failed.');
        }

        return result;
    }

    document.getElementById('addEquipmentButton').addEventListener('click', function () {
        form.reset();
        clearAssignments();
        document.getElementById('equipment_id').value = '';
        document.getElementById('equipmentModalTitle').textContent = 'Add Equipment';
        modal.show();
    });

    document.querySelectorAll('.edit-equipment').forEach(function (button) {
        button.addEventListener('click', function () {
            form.reset();
            clearAssignments();

            document.getElementById('equipment_id').value = this.dataset.id;
            document.getElementById('equipment_name').value = this.dataset.name;
            document.getElementById('equipment_order').value = this.dataset.order;
            document.getElementById('equipment_status').value = this.dataset.status;

            const value = this.dataset.units || '';
            const assigned = value ? value.split(',').filter(Boolean) : [];
            document.querySelectorAll('.unit-assignment').forEach(function (input) {
                input.checked = assigned.includes(input.value);
            });

            document.getElementById('equipmentModalTitle').textContent = 'Edit Equipment';
            modal.show();
        });
    });

    form.addEventListener('submit', async function (event) {
        event.preventDefault();

        const equipmentName = document.getElementById('equipment_name');
        equipmentName.value = equipmentName.value.trim();

        if (equipmentName.value === '') {
            await Swal.fire('Error', 'Equipment name is required.', 'error');
            return;
        }

        setSaving(true);

        try {
            const response = await fetch('ajax/save_equipment.php', {
                method: 'POST',
                body: new FormData(form)
            });
            const result = await getJsonResponse(response);

            if (!result.success) {
                await Swal.fire('Error', result.message, 'error');
                return;
            }

            await Swal.fire('Saved', result.message, 'success');
            window.location.reload();
        } catch (error) {
            await Swal.fire('Error', error.message || 'Unable to save equipment.', 'error');
        } finally {
            setSaving(false);
        }
    });

    document.querySelectorAll('.delete-equipment').forEach(function (button) {
        button.addEventListener('click', async function () {
            const confirmation = await Swal.fire({
                title: 'Delete ' + this.dataset.name + '?',
                text: 'This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Delete'
            });

            if (!confirmation.isConfirmed) {
                return;
            }

            try {
                const data = new FormData();
                data.append('id', this.dataset.id);
                data.append('csrf_token', form.querySelector('[name="csrf_token"]').value);

                const response = await fetch('ajax/delete_equipment.php', {
                    method: 'POST',
                    body: data
                });
                const result = await getJsonResponse(response);

                if (!result.success) {
                    await Swal.fire('Error', result.message, 'error');
                    return;
                }

                await Swal.fire('Deleted', result.message, 'success');
                window.location.reload();
            } catch (error) {
                await Swal.fire('Error', error.message || 'Unable to delete equipment.', 'error');
            }
        });
    });
});
