$(document).ready(function () {

    /**
     * show and hide divs based on the selected role
     */
    $(document).on('change', '#role', function () {
        $('.roles').addClass('d-none')
        if($(this).val()){
            $('.role_'+$(this).val()).removeClass('d-none')
        } else {
            // $('.roles').show()
        }
    });
    if($('#role').length){
        $('#role').trigger('change')
    }

    $( "#user" ).removeAttr('disabled')
    $( "#user" ).change(handleUserChange)
    $( "#user" ).keyup(handleUserChange)
    $( "#user" ).autocomplete({
        source: async function( request, response ) {
            // get users
            const data= await ajax({
                url: userAjaxRoute,
                data: {
                    q: request.term
                },
                method: 'get',
                no_load: true
            })
            // console.log(data);
            // response( data );
            response($.map(data, function (item) {
                return {
                    label: item.name+" "+item.phone,
                    // value: item.id
                    user_id: item.id
                };
            }));
        },
        minLength: 1,
        select: function( event, ui ) {
            // console.log(this.value)
            // console.log(ui.item.user_id)
            // $( "#user" ).val(this.value)
            $( "#user" ).val( ui.item.label )
            $( "#user_id" ).val( ui.item.user_id )
            // console.log( ui.item ?
            // "Selected: " + ui.item.label +" VALUE: " + ui.item.value :
            // "Nothing selected, input was " + this.value);
        },
        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }
    });

    $(document).on('change', '#stage_id', async function () {
        let html='<option value="">--</option>'
        const response= await ajax({
            url: stage_years_route,
            method: 'get',
            data:{
                stage_id: $(this).val() || null
            }
        })
        // console.log({response});
        for (const row of response) {
            const selected= row.id?.toString() == stage_year_id ? 'selected' : ''
            html+=`<option value="${row.id}" ${selected} >${row.current_description.name || ''}</option>`
        }
        $('#stage_year_id').html(html)
    });

    if($('#stage_id').length){
        $('#stage_id').trigger('change')
    }

    $(document).on('click', '.delete_device', async function () {
        const response= await ajax({
            url: delete_deivce_route.replace('USER_ID', $(this).attr('user_id')).replace('DEVICE_ID', $(this).attr('device_id')),
            method: 'delete',
        })
        // console.log({response});
        if (response?.message) {
            toasterSuccess(response?.message)
            $(this).closest('tr').remove()
        }
    });
    $(document).on('click', '.show_devices', async function () {
        $('.devices').html('')
        $('#user_devices_name').html($(this).data('user_name'))
        const response= await ajax({
            url: deivces_route.replace('USER_ID', $(this).data('user_id')),
            method: 'get',
        })
        // console.log({response});
        if (response?.length || 0) {
            $('#devices').modal('show')
        }
        let i= 0;
        for (const row of response) {
            $('.device_info_example #device_index').html(++i)
            $('.device_info_example #device_id').html(row?.device_id || '')
            $('.device_info_example #device_name').html(row?.device_name || '')
            $('.device_info_example #created_at').html(row?.created_at ? new Date(row?.created_at).toISOString().slice(0, 10) : '' )
            $('.device_info_example .delete_device').attr('user_id', row?.user_id || '').attr('device_id', row?.device_id || '')
            $('.devices').append("<tr> class='device_info'"+$('.device_info_example').html()+"</tr>")
        }
    });


    installDateRangeFields('.last_seen_at_from', '.last_seen_at_to')
});

//
const handleUserChange= function(){
    if (!$(this).val()?.trim().length) {
        $('#user_id').val('')
    }
}