import { buildEndpoint } from './urlBuilder';
document.addEventListener('DOMContentLoaded', function() {
    const switchStyleId = 'product-inactive-switch-style';
    if (!document.getElementById(switchStyleId)) {
        const style = document.createElement('style');
        style.id = switchStyleId;
        style.textContent = `
            .toggle-active-switch.switch-inactive {
                background-color: #ffd8dc;
                border-color: #dc3545;
            }
            .toggle-active-switch.switch-inactive:focus {
                border-color: #dc3545;
                box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
            }
        `;
        document.head.appendChild(style);
    }

    const productTable = $('#productTable');

    if (productTable.length) {
        const dataTable = productTable.DataTable({
            processing: true,
            serverSide: true,
            scrollX: true,
            autoWidth: false,
            ajax: {
                url: buildEndpoint('admin-fit/product/json'),
                type: 'GET'
            },
            columns: [
                { data: 'product_name', name: 'product_name', className: 'text-center' },
                { data: 'category_name', name: 'category_name', className: 'text-center' },
                { data: 'sale_price', name: 'sale_price', className: 'text-center' },
                { data: 'current_stock', name: 'current_stock', className: 'text-center' },
                {
                    data: null,
                    name: 'edit',
                    className: 'text-center',
                    orderable: false,
                    searchable: false,
                    render: function(data, type, row) {
                        const active = Number(row.is_active) === 1;
                        const switchId = `productActiveSwitch${row.id}`;
                        const checkedAttr = active ? 'checked' : '';
                        const inactiveClass = active ? '' : 'switch-inactive';
                        return `
                            <div class="d-flex justify-content-end align-items-center gap-2">
                                <div class="form-check form-switch m-0 d-flex align-items-center">
                                    <input class="form-check-input toggle-active-switch ${inactiveClass}" type="checkbox" role="switch" id="${switchId}" data-id="${row.id}" ${checkedAttr}>
                                    <label class="form-check-label ms-2" for="${switchId}">${active ? 'Activo' : 'Inactivo'}</label>
                                </div>
                                <a href="${buildEndpoint(`admin-fit/product/${row.id}/edit`)}" class="btn btn-sm btn-warning">Editar</a>
                            </div>
                        `;
                    }
                }
            ],
            columnDefs: [
                {
                    targets: -1,
                    className: 'text-center text-nowrap'
                }
            ],
            order: [[0, 'desc']]
            ,
            language: {
            "processing":     "Procesando...",
            "search":         "Buscar:",
            "lengthMenu":     "Mostrar _MENU_ registros",
            "info":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "infoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
            "infoFiltered":   "(filtrado de un total de _MAX_ registros)",
            "infoPostFix":    "",
            "loadingRecords": "Cargando...",
            "zeroRecords":    "No se encontraron resultados",
            "emptyTable":     "Ningún dato disponible en esta tabla",
            "paginate": {
                "first":      "Primero",
                "previous":   "Anterior",
                "next":       "Siguiente",
                "last":       "Último"
            },
            "aria": {
                "sortAscending":  ": Activar para ordenar la columna de manera ascendente",
                "sortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        }
        });

        productTable.on('change', '.toggle-active-switch', function() {
            const checkbox = $(this);
            const productId = Number(checkbox.data('id'));
            const nextActive = checkbox.is(':checked');
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

            checkbox.toggleClass('switch-inactive', !nextActive);
            checkbox.prop('disabled', true);

            fetch(buildEndpoint(`admin-fit/product/${productId}/set-active`), {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken || ''
                },
                body: JSON.stringify({ is_active: nextActive ? 1 : 0 })
            })
            .then(async (response) => {
                const data = await response.json().catch(() => ({}));
                if (!response.ok || data.success === false) {
                    throw new Error(data.message || 'No se pudo actualizar el estado del producto');
                }
                dataTable.ajax.reload(null, false);
            })
            .catch((error) => {
                alert(error.message || 'Error al actualizar estado del producto');
                const revertedActive = !nextActive;
                checkbox.prop('checked', revertedActive);
                checkbox.toggleClass('switch-inactive', !revertedActive);
                checkbox.prop('disabled', false);
            });
        });

    }
});