jQuery(document).ready(function ($) {
    'use strict';

    // Timepicker
    $('input.timepicker').timepicker({
        timeFormat: 'HH:mm',
        minTime: new Date(0, 0, 0, 0, 0, 0),
        maxTime: new Date(0, 0, 0, 23, 30, 0),
        startTime: new Date(0, 0, 0, 0, 0, 0),
        interval: 30
    });

    $('.dynamic-choice').on( 'click', function () {
        const $this = $(this),
            isChecked = $this.is(':checked');

        $this.parents('.choice-block').siblings('.choice-block').find('.subject-block')
            .toggleClass('disabled', isChecked)
            .find('input, select').prop('readonly', isChecked);

        $this.siblings('.subject-block')
            .toggleClass('disabled', !isChecked)
            .find('input, select').prop('readonly', !isChecked);
    });

    $('[data-toggle]').on('click', function() {
        const $this = $(this);
        $('#' + $this.data('toggle')).toggle($this.is(':checked'));
    } );

    const initSchedulerLists = () => {
        if ($('.md-select2').length) {
            $('.md-select2').select2({
                width: '100%',
                allowClear: true,
                closeOnSelect: false,
                language: {
                    noResults: () => 'Sin resultados',
                    searching: () => 'Buscando...',
                },
            });
        }

        if ($('.md-select2-campaign').length) {
            $('.md-select2-campaign').select2({
                width: '100%',
                allowClear: true,
                language: {
                    noResults: () => 'Sin resultados',
                    searching: () => 'Buscando...',
                },
            });
        }
    };

    const initValidator = (e) => {
        e.preventDefault();

        const $schedulerForm = $('#mdirector_scheduler_delivery_id');
        const $inputs = $schedulerForm.find('input[type="text"]');
        const $listsSelect = $('select[name="mdirector-scheduler-lists[]"]');

        let errors = false;

        $inputs.each(function () {
            const $input = $(this);

            if (!$input.val()) {
                $input.addClass('required');
                errors = true;
            } else {
                $input.removeClass('required');
            }
        });

        const listsSelected = $listsSelect.val();
        if (!listsSelected || !listsSelected.length) {
            $('.md-user-lists-container').find('.md-user-lists-label').addClass('required');
            errors = true;
        } else {
            $('.md-user-lists-container').find('.md-user-lists-label').removeClass('required');
        }

        if (errors) {
            return false;
        }

        $('#mdirector-scheduler-send').val('mdirector-scheduler-send');

        const $post = $('#post');
        if ($post.length) {
            $post.submit();
            return;
        }

        const { dispatch } = wp.data;
        const metadata = {
            'mdirector-scheduler-from': $('#mdirector-scheduler-from').val(),
            'mdirector-scheduler-subject': $('#mdirector-scheduler-subject').val(),
            'mdirector-scheduler-template': $('#mdirector-scheduler-template').val(),
            'mdirector-scheduler-campaign': $('#mdirector-scheduler-campaign').val(),
            'mdirector-scheduler-lists': $('select[name="mdirector-scheduler-lists[]"]').val() || [],
            'mdirector-scheduler-send': 'mdirector-scheduler-send',
        };

        try {
            dispatch('core/editor').editPost({
                meta: metadata
            });
            dispatch('core/editor').savePost();
        } catch (error) {
            console.info('error', error);
        }
    };

    const checkForValidator = (e) => {
        const $mdSchedulerIsActive = $('input[name="mdirector_scheduler_active"]');

        if ($mdSchedulerIsActive.is(':checked')) {
            return initValidator(e);
        }

        return true;
    };

    const initSchedulerValidator = () => {
        const $mdSchedulerSubmitButton = $('#mdscheduler_send_now');
        $mdSchedulerSubmitButton.on('click', initValidator);

        const $wpSubmitButton = $('#publish');
        $wpSubmitButton.on('click', checkForValidator);
    };

    initSchedulerLists();
    initSchedulerValidator();
});
