// Load Flatpickr libraries
const flatpickr = require("flatpickr").default;
import "flatpickr/dist/flatpickr.min.css";

// Load CodeMirror libraries
import CodeMirror from "codemirror";
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/monokai.css';
import 'codemirror/mode/xml/xml.js';


jQuery(document).ready(function ($) {

    function timeToString(timestamp) {
        var days = Math.floor(timestamp / (24 * 60 * 60)),
            hours = Math.floor(timestamp / (60 * 60)) % 24,
            minutes = Math.floor(timestamp / 60) % 60,
            seconds = Math.floor(timestamp / 1) % 60;

        var html = '';
        if (days > 0) {
            html += days + ' ' + rtm_mail_translation.time_days + ' ';
        }
        if (hours > 0) {
            html += hours + ' ' + rtm_mail_translation.time_hours + ' ';
        }
        if (minutes > 0) {
            html += minutes + ' ' + rtm_mail_translation.time_minutes + ' ';
        }
        html += seconds + ' ' + rtm_mail_translation.time_seconds;
        return html;
    }

    flatpickr("#rtm-date-range", {
        mode: "range",
        maxDate: "today",
        dateFormat: "d-m-Y",
        onChange: function (selectedDates, dateStr, instance) {
            let dates = instance.element.value.split('to');
            // If only one date is available
            if (!dates[1]) {
                let currentDate = new Date().toLocaleDateString('nl-NL', {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric',
                });
                // Set current date
                dateStr = dates[0] + ' to ' + currentDate;
            }
            instance.element.value = dateStr.replace('to', '-');
        },
    });

    // Get current date and set wordpress locale and timezone
    var currentDate = new Date();
    // Check if timezone is set to an UTC time
    if (rtm_mail_translation.wp_timezone.substr(0, 3) === 'UTC') {
        // Get current utc timestamp
        var utc_timestamp = Date.now();
        // Convert given utc times to milliseconds
        var time_in_seconds = convertToSeconds(rtm_mail_translation.wp_timezone.substr(4, rtm_mail_translation.wp_timezone.length));
        // Check if you need to add or substract
        var operation = rtm_mail_translation.wp_timezone.substr(3, 1)
        if (operation === '+') {
            // Update time
            currentDate.setTime(utc_timestamp + time_in_seconds)
        } else {
            // Update time
            currentDate.setTime(utc_timestamp - time_in_seconds)
        }
        // Convert to locale string and split the dates
        currentDate = splitDatetime(currentDate.toLocaleString('nl-NL', {timeZone: 'UTC'}));
    } else {
        currentDate = splitDatetime(currentDate.toLocaleString('nl-NL', {timeZone: rtm_mail_translation.wp_timezone}));
    }
    flatpickr("#rtm-queue-date", {
        enableTime: true,
        minDate: "today",
        dateFormat: "d-m-Y H:i",
        defaultHour: (parseInt(currentDate.hours) + 1), // suggestion +1hour
        defaultMinute: currentDate.minutes,
        onChange: function (selectedDates, dateStr, instance) {
            $("#queue-mail-log").prop("disabled", true);
            if ($(".log-select").length) {
                $(".log-select").each(function () {
                    if ($(this).is(':checked')) {
                        if ($(this).parent().parent().find('.badge').html() === rtm_mail_translation.status_sent || $(this).parent().parent().find('.badge').html() === rtm_mail_translation.status_queued) {
                            $("#queue-mail-log").prop("disabled", true);
                            return false;
                        } else if ($(this).parent().parent().find('.badge').html() !== rtm_mail_translation.status_sent && $(this).parent().parent().find('.badge').html() !== rtm_mail_translation.status_queued) {
                            if (dateStr) {
                                $("#queue-mail-log").prop("disabled", false);
                            }
                        }
                    }
                });
            } else {
                if (dateStr) {
                    $("#queue-mail-log").prop("disabled", false);
                }
            }
        },
    });

    if (document.getElementById('edit_body') != undefined) {
        var editor = CodeMirror.fromTextArea(document.getElementById('edit_body'), {
            lineNumbers: true,
            matchBrackets: true,
            styleActiveLine: true,
            theme: 'monokai',
            mode: 'xml',
            htmlMode: true,
            autoCloseTags: true,
        });
    }

    $('#rtm-mail').click(function () {
        $('#rtm-mail .dropdown-menu').css('display', 'none');
    });

    // Countdown timer for queued mails
    if ($('#queue__timestamp').length) {
        var queue_timestamp = (parseInt($('#queue__timestamp').val()) - (Date.now() / 1000));
        if (queue_timestamp > 0) {
            setInterval(function () {
                if (queue_timestamp > 0) {
                    queue_timestamp--;
                }
                var html = timeToString(queue_timestamp);
                $('.queue__countdown').html(html);
                if (queue_timestamp <= 0) {
                    setTimeout(function () {
                        location.reload()
                    }, 2000);
                }
            }, 1000)
        } else {
            $('.queue__countdown').html('0' + rtm_mail_translation.time_seconds);
        }
    }

    // Countdown timer for scheduled caught mails
    if ($('#schedule__timestamp').length) {
        var schedule_timestamp = (parseInt($('#schedule__timestamp').val()) - (Date.now() / 1000));
        if (schedule_timestamp > 0) {
            setInterval(function () {
                if (schedule_timestamp > 0) {
                    schedule_timestamp--;
                }
                var html = timeToString(schedule_timestamp);
                $('.schedule__countdown').html(html);

                if (schedule_timestamp <= 0) {
                    setTimeout(function () {
                        location.reload()
                    }, 2000);
                }
            }, 1000)
        } else {
            $('.schedule__countdown').html('0' + rtm_mail_translation.time_seconds);
        }
    }

    // Add field of outgoing email setting
    $('body').on('click', '#rtm-mail #add_outgoing_field', function () {
        // random number for semi "unique" box ids
        let box_id = Math.floor(Math.random() * 999);
        var html = `
        <tr class="outgoing-mail-row" data-boxid="${box_id}">
            <td class="outgoing-mail-cell email-cell">
                <input type="text" name="option_email[]" class="option-email"
                       placeholder="${rtm_mail_translation.type_address}" />
            </td>
            <td class="outgoing-mail-cell type-cell">
                <select class="outgoing_type" name="outgoing_type[]">
                    <option value="cc">CC</option>
                    <option value="bcc">BCC</option>
                    <option value="recipient">Recipient</option>
                </select>
            </td>
            <td class="outgoing-mail-cell button-cell">
                 <button type="button" name="remove_outgoing"
                        class="button button-invert-remove remove_outgoing_field"
                        data-boxid="${box_id}"
                        style="padding: 0 12px">-
                </button>
            </td>
        </tr>
        `;
        $("#outgoing__list").append(html);
    });

    // Remove field of outgoing email setting
    $('body').on('click', '#rtm-mail .remove_outgoing_field', function () {
        let box_id = $(this).attr('data-boxid');
        $("[data-boxid='" + box_id + "'").remove();
        $(this).remove();
    });

    // Toggle search filters
    $('body').on('click', '#rtm-mail .filter-box .filter-label-box .filter-label', function () {
        $('#rtm-mail .filter-box .filter-input').slideToggle('fast', function () {
            if ($(this).is(':visible')) {
                $(this).css('display', 'flex');
            }
        });
        $(this).find('.filter__icon').toggleClass('fa-caret-down').toggleClass('fa-caret-up');
    });

    // Close modal
    $('body').on('click', '#rtm-mail .modal-close', function () {
        let log_id = $(this).attr('data-id');
        $('#modal_' + log_id).fadeOut(250);
    });

    // Preview mail modal
    $('body').on('click', '#rtm-mail #preview_mail', function () {
        $('.modal-container').css('height', '60vh');
        $('#modal_preview').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #add_receiver', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#add_type').val('receiver');
        $('#modal_add_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #add_cc', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#add_type').val('cc');
        $('#modal_add_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #add_bcc', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#add_type').val('bcc');
        $('#modal_add_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #remove_receiver', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#remove_type').val('receiver');
        $('#remove_mail_list').html('');
        let address_list = $("#edit_receiver").val().split(';');

        if (address_list != null && address_list[0] != null) {
            $.each(address_list, function (index, address) {
                if (address != null && address != '') {
                    let html = '<div class="address_remove_input"><input type="text" name="address_remove" class="address_to_remove" value="' + address + '" disabled /><button type="button" name="remove-receiver" class="button button-invert-remove remove_address">-</button></div>';
                    $('#remove_mail_list').append(html);
                }
            });
        }

        $('#modal_remove_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #remove_cc', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#remove_type').val('cc');
        $('#remove_mail_list').html('');
        let address_list = $("#edit_cc").val().split(';');

        if (address_list != null && address_list[0] != null) {
            $.each(address_list, function (index, address) {
                if (address != null && address != '') {
                    let html = '<div class="address_remove_input"><input type="text" name="address_remove" class="address_to_remove" value="' + address + '" disabled /><button type="button" name="remove-receiver" class="button button-invert-remove remove_address">-</button></div>';
                    $('#remove_mail_list').append(html);
                }
            });
        }

        $('#modal_remove_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #remove_bcc', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#remove_type').val('bcc');
        $('#remove_mail_list').html('');
        let address_list = $("#edit_bcc").val().split(';');

        if (address_list != null && address_list[0] != null) {
            $.each(address_list, function (index, address) {
                if (address != null && address != '') {
                    let html = '<div class="address_remove_input"><input type="text" name="address_remove" class="address_to_remove" value="' + address + '" disabled /><button type="button" name="remove-receiver" class="button button-invert-remove remove_address">-</button></div>';
                    $('#remove_mail_list').append(html);
                }
            });
        }

        $('#modal_remove_mail').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail .remove_address', function () {
        $(this).parent().remove();
    });

    $('body').on('click', '#rtm-mail #save_added_address', function () {
        let address_type = $("#add_type").val();
        let address = $("#add_mail_address").val();
        if (address_type === 'receiver') {
            if ($("#edit_receiver").val() !== '') {
                $("#edit_receiver").val($("#edit_receiver").val() + ';' + address);
            } else {
                $("#edit_receiver").val(address);
            }
        } else if (address_type === 'cc') {
            if ($("#edit_cc").val() !== '') {
                $("#edit_cc").val($("#edit_cc").val() + ';' + address);
            } else {
                $("#edit_cc").val(address)
            }
        } else if (address_type === 'bcc') {
            if ($("#edit_bcc").val() !== '') {
                $("#edit_bcc").val($("#edit_bcc").val() + ';' + address);
            } else {
                $("#edit_bcc").val(address)
            }
        }
        $("#add_mail_address").val('');
        $('#modal_add_mail').fadeOut(250);
    });

    $('body').on('click', '#rtm-mail #save_removed_address', function () {
        let address_type = $("#remove_type").val();
        let addresses = '';

        $(".address_to_remove").each(function () {
            if (addresses === '') {
                addresses += $(this).val();
            } else {
                addresses += ';' + $(this).val();
            }
        });

        $("#edit_" + address_type).val(addresses);

        $('#modal_remove_mail').fadeOut(250);
    });

    $('body').on('click', '#rtm-mail #delete_log', function () {
        $('.modal-container').css('height', 'auto');
        $('#modal_delete_log').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #send_mail', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#modal_send_log').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #delete-submit', function () {
        $('.modal-container').css({
            width: 'fit-content',
            height: 'auto',
        });
        $('#modal_delete_log_rows').fadeIn(250);
    });

    // Preview overview modal
    $('body').on('click', '#rtm-mail #action-preview', function () {
        $('.modal-container').css({height: '60vh', width: '35vw'});
        $('#rtm-mail .mail-preview').attr("src", "?page=rtm-mail-details&mail_preview=true&log_id=" + $(this).attr('data-id'));
        $('#modal_action_preview').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #action-send', function () {
        $('.modal-container').css({height: 'auto', width: '17vw'});
        $('#send_log_id').val($(this).attr('data-id'));
        $('#modal_log_action_send').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #action-delete', function () {
        $('.modal-container').css({height: 'auto', width: '17vw'});
        $('#delete_log_id').val($(this).attr('data-id'));
        $('#modal_log_action_delete').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #send-submit', function () {
        $('.modal-container').css('height', 'auto');
        $('#modal_send_log_rows').fadeIn(250);
    });

    $('body').on('change', '#rtm-mail .log-select, #rtm-mail #cb-select-all-1, #rtm-mail #cb-select-all-2', function () {
        $("#send-submit").prop("disabled", true);
        $("#delete-submit").prop("disabled", true);
        $("#queue-mail-log").prop("disabled", true);
        $("#dequeue-mail-log").css('display', 'none');
        $(".log-select").each(function () {
            if ($(this).is(':checked')) {
                $("#delete-submit").prop("disabled", false);
                $("#send-submit").prop("disabled", false);
                if ($(this).parent().parent().find('.badge').html() === rtm_mail_translation.status_queued) {
                    $("#queue-mail-log").prop("disabled", true);
                    $("#dequeue-mail-log").css('display', 'inline');
                    return false;
                } else {
                    $("#dequeue-mail-log").css('display', 'none');
                    if ($('#rtm-queue-date').val()) {
                        $("#queue-mail-log").prop("disabled", false);
                    }
                }
            }
        });
    });

    // Sender options select
    $('body').on('change', '#rtm-mail .sender-preset', function () {
        let option = $(this).val();
        if (option === 'admin_user') {
            $('#admin-preset-list').css('display', 'block');
        } else if (option === 'custom') {
            $('#admin-preset-list').css('display', 'none');
            $('#sender_preset_title').val('');
            $('#sender_preset_address').val('');
        } else {
            $('#admin-preset-list').css('display', 'none');
            let sender_options = option.split(';');
            $('#sender_preset_title').val(sender_options[0]);
            $('#sender_preset_address').val(sender_options[1]);
        }
    });

    $('body').on('change', '#rtm-mail .admin-sender-preset', function () {
        let option = $(this).val();
        let sender_options = option.split(';');
        $('#sender_preset_title').val(sender_options[0]);
        $('#sender_preset_address').val(sender_options[1]);
    });

    $('body').on('click', '#rtm-mail .event-detail-block', function () {
        let target = $(this).parent().find('.event-details-expand');
        $(target).slideToggle();
        $(this).find('.caret__icon').toggleClass('fa-caret-down').toggleClass('fa-caret-left');
    });

    // info dashboard icon
    $('body').on('click', '#rtm-mail .icon__info', function () {
        $('.modal-container').css('height', 'auto');
        $('#' + $(this).attr('data-target')).fadeIn(250);
    });

    $('body').on('click', '#rtm-mail .toggle__dropdown', function () {
        $('.' + $(this).attr('data-target')).css('display', 'block');
    });

    // nl-NL locale to splitted date object
    function splitDatetime(datetimeStr) {
        var date_time = datetimeStr.split(' ');
        var date_split = date_time[0].split('-');
        var time_split = date_time[1].split(':');
        return {
            day: date_split[0],
            month: date_split[1],
            year: date_split[2],
            hours: time_split[0],
            minutes: time_split[1],
            seconds: time_split[2],
        }
    }

    // Calculates UTC string to unix time seconds
    function convertToSeconds(time_str) {
        if (time_str) {
            var time = time_str.split(':');
            var hours = parseInt(time[0]);
            var minutes = parseInt(time[1]);
            // Convert hours and minutes to time in seconds
            return (hours * (60 * (60 * 1000))) + (minutes * (60 * 1000));
        } else {
            // Empty string == no added time
            return 0
        }
    }

    $('body').on('click', '#rtm-mail #clear-events', function () {
        $('.modal-container').css({height: 'auto', width: '17vw'});
        $('#modal_clear_events').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail .mobile-link-toggle', function () {
        $(this).find('.fas').toggleClass('fa-bars').toggleClass('fa-times');
        $('.navbar-mobile-container').fadeToggle("fast", function () {
            $('.navbar-mobile').animate({
                width: "toggle"
            });
        });
    });

    $('body').on('click', '#rtm-mail #queue-mail-log', function () {
        $('.modal-container').css({height: 'auto', width: 'auto'});
        $('.modal__datetime').html($('#rtm-queue-date').val());
        $('#hidden__queue__date').val($('#rtm-queue-date').val());
        $('#modal_log_queue').fadeIn(250);
    });

    $('body').on('click', '#rtm-mail #dequeue-mail-log', function () {
        $('.modal-container').css({height: 'auto', width: 'auto'});
        $('#modal_log_dequeue').fadeIn(250);
    });

    $('body').on('change', '#rtm-mail #enable__smtp', function() {
       if ($(this).is(':checked')) {
           $('.smtp__option').css({
               opacity: '1.0',
               pointerEvents: 'auto',
           });
       }  else {
           $('.smtp__option').css({
               opacity: '0.4',
               pointerEvents: 'none',
           });
       }
    });

    $('body').on('change', '#rtm-mail #enable__authentication', function() {
        if ($(this).is(':checked')) {
            $('.smtp__credentials').css('display', 'flex');
        }  else {
            $('.smtp__credentials').css('display', 'none');
        }
    });

    $('body').on('change', '#rtm-mail #option__sms__enabled', function() {
        if ($(this).is(':checked')) {
            $('.option-twilio-settings').css('display', 'block');
        }  else {
            $('.option-twilio-settings').css('display', 'none');
        }
    });
    const phoneInputField = document.querySelector("#phone__input");
    if (phoneInputField) {
        const phoneInput = window.intlTelInput(phoneInputField, {
            preferredCountries: ["us", "gb", "nl", "de"],
            separateDialCode: true,
            utilsScript:
                "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
        });
    }

    $('#rtm-mail-settings').submit((e) => {
        const phoneNumber = phoneInput.getNumber();
        $('#phone__number').val(phoneNumber);
        console.log(phoneNumber);
    });

    $('body').on('click', '#rtm-mail #resend_mail', function () {
        $('.modal-container').css({height: 'auto', width: 'auto'});
        $('#modal_resend_mail').fadeIn(250);
        $('.modal__address').html($(this).attr('data-address'));
        $('#resend__address').val($(this).attr('data-address'));
    });

    $('#rtm-mail .receiver-status-button-toggle').click(function() {
        let index = $(this).data('index') || 0;
        index++;
        $('.receiver-status-button-toggle').data('index', 0).css({
            background: '#fff',
            color: '#3c434a',
            border: '1px solid #c3c4c7',
        });
        if (index === 1) {
            $(this).css({
                background: '#bf0707',
                color: '#fff',
                border: '1px solid transparent',
            });
            if ($(this).attr('data-type') === 'sent') {
                $(".receiver-status-table tr .sent-cell").filter(function() {
                    $(this).parent().toggle($(this).find('i').hasClass('status-off'))
                });
            } else {
                $(".receiver-status-table tr .opened-cell").filter(function() {
                    $(this).parent().toggle($(this).find('i').hasClass('status-off'))
                });
            }
        } else if (index === 2) {
            $(this).css({
                background: '#05988a',
                color: '#fff',
                border: '1px solid transparent',
            });
            if ($(this).attr('data-type') === 'sent') {
                $(".receiver-status-table tr .sent-cell").filter(function() {
                    $(this).parent().toggle($(this).find('i').hasClass('status-on'))
                });
            } else {
                $(".receiver-status-table tr .opened-cell").filter(function() {
                    $(this).parent().toggle($(this).find('i').hasClass('status-on'))
                });
            }
        } else {
            $(".receiver-status-table tr").css('display', 'table-row');
            $(this).css({
                background: '#fff',
                color: '#3c434a',
                border: '1px solid #c3c4c7',
            });
            index = 0;
        }
        $(this).data('index', index);
    });

    $('#rtm-mail .bulk__action').change(function() {
        if ($(this).val()) {
            $('#apply__bulk__action').prop('disabled', false)
        } else {
            $('#apply__bulk__action').prop('disabled', true)
        }
    });

    $('#apply__bulk__action').click((e) => {
        let action = $('.bulk__action').val();
        if (action === 'send') {
            $('.modal-container').css('height', 'auto');
            $('#modal_send_log_rows').fadeIn(250);
        } else if (action === 'delete') {
            $('.modal-container').css({
                width: 'fit-content',
                height: 'auto',
            });
            $('#modal_delete_log_rows').fadeIn(250);
        }
    });
})
