(function ($) {
    'use strict';

    function initSelect2($elements) {
        $elements.each(function () {
            let $element = $(this);
            let options = {};
            let placeholder = $element.data('placeholder') || $element.attr('placeholder');
            let allowClear = $element.data('allow-clear');

            if (placeholder) {
                options.placeholder = placeholder;
            }

            if (allowClear === true || allowClear === 'true' || allowClear === 1 || allowClear === '1') {
                options.allowClear = true;
            }

            $element.select2(options);
        });
    }

    let dataTableDateFormats = [
        'DD-MM-YYYY HH:mm:ss',
        'DD-MM-YYYY HH:mm',
        'DD-MM-YYYY',
        'DD/MM/YYYY HH:mm:ss',
        'DD/MM/YYYY HH:mm',
        'DD/MM/YYYY',
        'DD-MM'
    ];

    function normalizeDataTableDate(value) {
        if (value === null || value === undefined) {
            return '';
        }

        return $('<div>').html(String(value)).text().replace(/\s+/g, ' ').trim();
    }

    function parseDataTableDate(value) {
        let normalized = normalizeDataTableDate(value);

        if (!normalized || normalized === '-') {
            return null;
        }

        let match = normalized.match(/\d{1,2}[-/]\d{1,2}(?:[-/]\d{4})?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?/);

        if (!match) {
            return null;
        }

        let date = moment(match[0], dataTableDateFormats, true);

        return date.isValid() ? date.valueOf() : null;
    }

    if ($.fn.dataTable) {
        $.fn.dataTable.ext.type.detect.unshift(function (data) {
            return parseDataTableDate(data) !== null ? 'admin-date-fr' : null;
        });

        $.fn.dataTable.ext.type.order['admin-date-fr-pre'] = function (data) {
            let timestamp = parseDataTableDate(data);

            return timestamp === null ? 0 : timestamp;
        };
    }

    $('[data-toggle="tooltip"]').tooltip();
    initSelect2($('.select2'));
    $('.datetimepicker').datetimepicker({
        locale: 'fr',
        format: 'YYYY-MM-DD HH:mm'
    });
    $('.confirm-deletable').on('click', function (e) {
        $("#btnDeletable").attr('href', $(this).attr('href'));
        $("#confirmDeletable .modal-body").text($(this).attr('data-title'));
        $("#confirmDeletable").modal('show');
        e.preventDefault();

        return false;
    });
    $('.confirm-modification').on('click', function(e){
        $("#btnModification").attr('href', $(this).attr('href'));
        $("#confirmModification .modal-body").text($(this).attr('data-title'));
        $("#confirmModification").modal('show');
        e.preventDefault();

        return false;
    });
    $(document).on('submit', 'form[data-confirm-submit]', function () {
        let message = $(this).data('confirm-message') || 'Confirmer cette action ?';

        return window.confirm(message);
    });
    let pendingCreditConfirmation = null;

    function formatCreditAmount(amountInCents) {
        return (amountInCents / 100).toLocaleString('fr-FR', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }) + ' €';
    }

    function parseInteger(value) {
        let parsed = parseInt(value, 10);

        return Number.isNaN(parsed) ? 0 : parsed;
    }

    function computeCreditAmount($form, action) {
        let total = 0;

        $form.find('input[name^="credit_quantities["]').each(function () {
            let quantityOrdered = Math.max(1, parseInteger($(this).data('quantity-ordered')));
            let lineTotalTtc = Math.max(0, parseInteger($(this).data('line-total-ttc')));
            let quantityRefunded = action === 'full'
                ? quantityOrdered
                : Math.max(0, Math.min(quantityOrdered, parseInteger($(this).val())));

            if (quantityRefunded <= 0) {
                return;
            }

            total += Math.round((lineTotalTtc * quantityRefunded) / quantityOrdered);
        });

        let shippingPaidTtc = Math.max(0, parseInteger($form.data('shipping-paid-ttc')));
        let shippingMode = String($form.find('[name="shipping_refund_mode"]').val() || 'none');
        let shippingAmount = 0;

        if (action === 'full') {
            shippingAmount = shippingPaidTtc;
        } else if (shippingMode === 'full') {
            shippingAmount = shippingPaidTtc;
        } else if (shippingMode === 'percent') {
            let shippingPercent = Math.max(0, Math.min(100, parseInteger($form.find('[name="shipping_refund_percent"]').val())));
            shippingAmount = Math.round((shippingPaidTtc * shippingPercent) / 100);
        }

        return total + shippingAmount;
    }

    function buildCreditConfirmationContent(action, amountInCents, refundState) {
        let amount = formatCreditAmount(amountInCents);
        let title = 'Confirmer l\'action';
        let body = '';

        if (action === 'cancel') {
            title = 'Annuler l\'avoir';
            body += '<p>Vous allez annuler l\'avoir de <strong>' + amount + '</strong>.</p>';
            body += '<p>Le numéro et le détail de l\'avoir actuel seront supprimés.</p>';

            return {title: title, body: body};
        }

        if (action === 'full') {
            title = 'Générer un avoir total';
        } else {
            title = 'Générer l\'avoir sélectionné';
        }

        body += '<p>Vous allez générer un avoir de <strong>' + amount + '</strong>.</p>';

        if (refundState === 'checked') {
            body += '<p class="text-warning">Le client recevra un remboursement automatique de <strong>' + amount + '</strong> sur sa carte bancaire.</p>';
        } else if (refundState === 'unchecked') {
            body += '<p class="text-muted">Le client ne recevra pas de remboursement automatique tant que la case de remboursement carte n\'est pas cochée.</p>';
        } else if (refundState === 'unavailable') {
            body += '<p class="text-muted">Le remboursement automatique par carte n\'est pas disponible pour cette commande.</p>';
        }

        return {title: title, body: body};
    }

    $(document).on('click', 'button[data-credit-confirm]', function () {
        $(this.form).data('creditSubmitter', this);
    });
    $(document).on('submit', 'form[data-credit-confirm-form]', function (e) {
        let $form = $(this);

        if ($form.data('creditConfirmationAccepted') === true) {
            $form.removeData('creditConfirmationAccepted');

            return true;
        }

        let submitter = e.originalEvent && e.originalEvent.submitter
            ? e.originalEvent.submitter
            : $form.data('creditSubmitter');

        if (!submitter) {
            submitter = $form.find('button[data-credit-confirm="partial"], button[data-credit-confirm="full"], button[data-credit-confirm="cancel"]').get(0);
        }

        if (!submitter) {
            return true;
        }

        let action = $(submitter).data('credit-confirm');
        let amountInCents = action === 'cancel'
            ? Math.max(0, parseInteger($(submitter).data('credit-amount-ttc')))
            : computeCreditAmount($form, action);
        let $refundCheckbox = $form.find('input[name="refund_to_card"]');
        let refundState = 'none';

        if (action !== 'cancel') {
            if ($refundCheckbox.length === 0) {
                refundState = 'unavailable';
            } else {
                refundState = $refundCheckbox.is(':checked') ? 'checked' : 'unchecked';
            }
        }

        let content = buildCreditConfirmationContent(action, amountInCents, refundState);

        pendingCreditConfirmation = {
            form: this,
            submitter: submitter
        };

        $('#creditConfirmModalTitle').text(content.title);
        $('#creditConfirmModalBody').html(content.body);
        $('#creditConfirmModal').modal('show');

        e.preventDefault();

        return false;
    });
    $('#creditConfirmModalSubmit').on('click', function () {
        if (!pendingCreditConfirmation) {
            return;
        }

        let form = pendingCreditConfirmation.form;
        let submitter = pendingCreditConfirmation.submitter;
        let $form = $(form);

        pendingCreditConfirmation = null;
        $form.data('creditConfirmationAccepted', true);
        $form.removeData('creditSubmitter');
        $('#creditConfirmModal').modal('hide');

        if (typeof form.requestSubmit === 'function' && submitter) {
            form.requestSubmit(submitter);

            return;
        }

        if (submitter && submitter.name) {
            $form.find('input[data-credit-submit-fallback="true"]').remove();
            $('<input>')
                .attr({
                    type: 'hidden',
                    name: submitter.name,
                    value: submitter.value,
                    'data-credit-submit-fallback': 'true'
                })
                .appendTo($form);
        }

        form.submit();
    });
    $('#creditConfirmModal').on('hidden.bs.modal', function () {
        if (pendingCreditConfirmation) {
            $(pendingCreditConfirmation.form).removeData('creditSubmitter');
        }

        pendingCreditConfirmation = null;
    });

    window.setTimeout(function () {
        $(".alert alert-success").fadeTo(500, 0).slideUp(500, function () {
            $(this).remove();
        });
    }, 4000);

    jQuery('.datetimepicker').datetimepicker({
        locale: 'fr',
        format: 'YYYY-MM-DD HH:mm'
    });
    $('.trumbowyg').trumbowyg({
        lang: 'fr',
        semantic: false,
        removeformatPasted: true,
        svgPath: '/bundles/cpcreationviticore/fonts/icons.svg',
        btns: [
            ['viewHTML'],
            ['undo', 'redo'], // Only supported in Blink browsers
            ['formatting'],
            ['strong', 'em', 'del'],
            ['superscript', 'subscript'],
            ['link'],
            ['removeformat'],
            ['fullscreen']
        ]

    });

    $('.select2-tag').select2({
        tags: true,
        tokenSeparators: [",", " "],
        createTag: function (tag) {
            return {
                id: tag.term,
                text: tag.term,
                // add indicator:
                isNew: true
            };
        },
    }).on("select2-tag:select", function (e) {
        if (e.params.data.isNew) {
            jQuery(this).find('[value="' + e.params.data.id + '"]').replaceWith('<option selected value="' + e.params.data.code + '">' + e.params.data.code + '</option>');
        }
    });

    $(document).ready(function () {
        $('.dataTable').each(function () {
            let $table = $(this);
            let order = $table.data('order');
            let options = {
                stateSave: true,
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/French.json"
                }
            };

            if (Array.isArray(order) && order.length > 0) {
                options.order = order;
                options.stateLoadParams = function (settings, data) {
                    data.order = order;
                };
            }

            $table.DataTable(options);
        });
    });

    $('.remove-media').on('click', function (e) {
        e.preventDefault();
        let id = $(this).data('id');
        $.ajax({
            type: 'GET',
            url: Routing.generate('media_delete', {id: id}),
            dataType: 'json',
            success: function (result) {
                $(".media-file[data-id='" + id + "']").remove();

                return;
            },
            error: function () {


                return;
            },
        });
        return false;
    });
    if ($('.insta-photo').length)
    {
        let username = $('.insta-photo').data('username');
        $.get("https://www.instagram.com/"+username+"/?__a=1")
            .done(function(data) {
                // getting the url
                var photoURL = data["graphql"]["user"]["profile_pic_url_hd"];
                // update img element
                $(".insta-photo").attr("src",photoURL)
            })
    }
   
})($);
