$(function () {

    const showError = (input, message) => {
        $(input).after(`<span class="text-danger">${message}</span>`)
    }

    const clearError = (input) => {
        $(input).next('.text-danger').remove()
    }

    $('#form').on('submit', (e) => {
        e.preventDefault()
        let hasErrors = false

        const formData = {
            link: $('#link').val(),
        }

        clearError('#link')

        if (!formData.link) {
            showError('#link', 'El link es requerido')
            hasErrors = true
        }

        if (hasErrors) return

        $.ajax({
            url: './routes/web.php',
            type: 'POST',
            data: { REQUEST_URI: '/videos/store', data: formData, },
            success: (response) => {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '¡Exito!',
                        text: response.message,
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        window.location.href = '?page=videos'
                    });
                }else{
                    Swal.fire({
                        icon: 'error',
                        title: '¡Error!',
                        text: 'Hubo un error al procesar la solicitud',
                        showConfirmButton: false,
                        timer: 1500
                    });
                }
            },
            error: (error) => {
                console.log('Error: ', error)
                Swal.fire({
                    icon: 'error',
                    title: '¡Error!',
                    text: 'Hubo un error al procesar la solicitud'
                });
            }
        })
    })
})