import { numberWithCommas, formatPriceElement, parsePrice } from "./utils";

; (function ($) {

    const loadBuyerProvinces = function (country, selectedProvince) {
        var $province = $('select[name="buyer_province"]');
        $province.html('<option value="">' + anbarak.i18n.select_province + '</option>');

        if (!country) return;

        $.get(anbarak.ajax_url, {
            action: 'anbarak_get_provinces',
            country: country,
            security: anbarak.nonce
        }, function (res) {
            if (res.success && res.data.provinces) {
                $.each(res.data.provinces, function (code, name) {
                    $province.append(
                        $('<option>', {
                            value: code,
                            text: name,
                            selected: selectedProvince && selectedProvince === code
                        })
                    );
                });
            }
        });
    }

    $(document).on('change', '#buyer_country', function () {
        loadBuyerProvinces($(this).val(), '');
    });

    const fillBuyerFromCustomer = function (customer) {
        var $form = $('#new-order-form');

        $form.find('input[name="buyer_name"]').val(customer.first_name || '');
        $form.find('input[name="buyer_last_name"]').val(customer.last_name || '');
        $form.find('input[name="buyer_email"]').val(customer.email || '');
        $form.find('input[name="buyer_address"]').val(customer.address || '');
        $form.find('input[name="buyer_postal"]').val(customer.postal || '');

        if (customer.country && $form.find('select[name="buyer_country"]').length) {
            $form.find('select[name="buyer_country"]').val(customer.country);
            loadBuyerProvinces(customer.country, customer.province || '');
        } else {
            $form.find('select[name="buyer_province"]').val(customer.province || '');
        }
    }

    const resetBuyerFields = function () {
        var $form = $('#new-order-form');

        $form.find('input[name="buyer_name"]').val('');
        $form.find('input[name="buyer_last_name"]').val('');
        $form.find('input[name="buyer_email"]').val('');
        $form.find('input[name="buyer_address"]').val('');
        $form.find('input[name="buyer_postal"]').val('');
        $form.find('select[name="buyer_province"]').val('');
    }

    $(document).on('selectx:select', '.buyer-phone-selectx', function (event, customer) {
        fillBuyerFromCustomer(customer);
    });

    $(document).on('selectx:clear', '.buyer-phone-selectx', function () {
        resetBuyerFields();
    });

    const getTotal = function () {
        var total = 0;
        $('.new-order__products-list .product').each(function () {
            var $product = $(this);
            var price = $product.find('input[name="price"]').val();
            var qty = $product.find('input[name="qty"]').val();
            total += parsePrice(price) * +qty;
        })

        return total;
    }

    const recalculateTotals = function () {
        var total = getTotal();
        var discount = 0;

        recalculateDiscountPercent();
        discount = $('#new-order-discount').attr('data-discount') || 0;
        // calc discount
        total -= discount;

        $('.submit-order-modal .total-price').html(numberWithCommas(total))

        // attach listeners
        $('.new-order__products-list input[name="price"]').off('keyup').on('keyup', function () {
            recalculateTotals()
        })
        $('.new-order__products-list input[name="qty"]').off('keyup change').on('keyup change', function () {
            recalculateTotals()
        })

        if ($('.new-order__products-list tbody tr').length) {
            $('#submit-sell').prop('disabled', false);
        } else {
            $('#submit-sell').prop('disabled', true);
        }
    }

    const recalculateDiscountPercent = function () {
        var total = getTotal();
        var discountPercent = $('#new-order-discount-percent').attr('data-value') || 0;
        var discount = total * discountPercent / 100;
        $('#new-order-discount').val(Math.round(discount));
        $('#new-order-discount').attr('data-discount', Math.round(discount));
        formatPriceElement($('#new-order-discount'));

    }

    // discount inputs
    $('#new-order-discount-percent').on('change blur', function () {
        $(this).attr('data-value', $(this).val());
        recalculateDiscountPercent();
        recalculateTotals();
    })

    // discount inputs
    $('#new-order-discount').on('change', function () {
        var total = getTotal();
        var discount = $('#new-order-discount').val().replace(/\D/g, '');
        var discountPercent = discount / total * 100;
        $(this).attr('data-discount', $(this).val().replace(/\D/g, ''));
        $('#new-order-discount-percent').val(discountPercent.toFixed(2));
        $('#new-order-discount-percent').attr('data-value', discountPercent);
        recalculateTotals()
    })

    const addProductToProductsList = function (productData) {
        var $templateContent = $($('#new-order-product-item').html());

        $templateContent.find('td.name .title').html(productData.title)
        $templateContent.find('td.name .vars').html(productData.vars)
        $templateContent.find('td.sku').html(productData.sku || '')
        $templateContent.find('td.qty input').val(1)
        $templateContent.find('td.price input').val(productData.unit_price)
        $templateContent.attr('data-id', productData.id)
        $templateContent.attr('data-unit-price', productData.unit_price)

        $('.new-order__products-list tbody').append($templateContent);
        $('.new-order__products-list .thousand-separator').each(function () {
            formatPriceElement($(this));
        })

        recalculateTotals();
    }

    const clearSearchResult = function () {
        var $resultContainer = $('.product-select-list');
        $resultContainer.html('')
        $('.submit-order-product-search').removeClass('active');
    }

    document.addEventListener('keydown', function (event) {
        if ((event.ctrlKey || event.metaKey) && event.key === 'f') {
            event.preventDefault();
            $('form.submit-order-product-search input[name="q"]').focus();
        }
    });

    document.addEventListener('keydown', function (event) {
        if ((event.ctrlKey || event.metaKey) && event.key === 'o') {
            event.preventDefault();
            MicroModal.show('modal-new-order');
            $('form.submit-order-product-search input[name="q"]').focus();
        }
    });

    $('form.submit-order-product-search').submit(function (e) {
        e.preventDefault();
        var $resultContainer = $('.product-select-list');
        clearSearchResult();
        var ajaxData = $(this).serialize();

        $.ajax({
            method: 'GET',
            url: anbarak.ajax_url,
            data: ajaxData,
            dataType: "html"
        }).done(function (html) {
            if (1 == $(html).length) {
                addProductToProductsList({
                    'id': $(html).data('id'),
                    'title': $(html).find('.name .title').html(),
                    'vars': $(html).find('.name .vars').html(),
                    'sku': $(html).data('sku'),
                    'unit_price': $(html).data('unit-price'),
                    'qty': 1
                });

                $('form.submit-order-product-search input[name="q"]').val('').focus();

            } else {
                $('.submit-order-product-search').addClass('active');
                if (html.length) {
                    $resultContainer.html(html)
                } else {
                    $resultContainer.html(anbarak.i18n.nothing_found)
                }
            }

        }).fail(function (response) {
            alert(anbarak.i18n.nothing_found);
            $('.submit-order-product-search').removeClass('active');
        })

    })

    $(document).on('click', '.product-select-list .product', function (e) {
        var html = $(this);

        addProductToProductsList({
            'id': $(html).data('id'),
            'title': $(html).find('.name .title').html(),
            'vars': $(html).find('.name .vars').html(),
            'sku': $(html).data('sku'),
            'unit_price': $(html).data('unit-price'),
            'qty': 1,
        });

        clearSearchResult();
    });

    $('form.submit-order-product-search input[name="q"]').on('keyup', function () {
        clearSearchResult();
    })

    $('.submit-order-modal .modal__container').click(function (e) {
        if ($(e.target).hasClass('product')) return;
        clearSearchResult();
    })

    /**
    * New order button click
    */
    $(document).on('click', '.btn-submit-sell', function (e) {
        e.preventDefault();
        var $form = $(this).parents("form");
        var $tr = $(this).parents("tr");

        $form.find(".actionName")
            .attr("name", $(this).attr("name"));

        var variation_id = $tr.find('input[name="var_id"]').val();
        var product_id = $tr.find('input[name="product_id"]').val();

        $form.find(".actionName").attr("name", $(this).attr("name"));
        $form.find("input[name='pid']").val(product_id);

        if (variation_id) {
            $form.find("input[name='vid']").val(variation_id);
        } else {
            $form.find("input[name='vid']").val(0);
        }

        $.ajax({
            method: 'GET',
            url: anbarak.ajax_url,
            data: {
                id: product_id,
	                action: 'anbarak_get_new_order_product_json',
                security: anbarak.nonce
            },
            dataType: "json"
        }).done(function (data) {
            addProductToProductsList({
                'id': data.id,
                'title': data.title,
                'vars': data.vars_html,
                'sku': data.sku,
                'unit_price': data.unit_price,
                'qty': 1,
            });

        }).fail(function (response) {
            alert(anbarak.i18n.connection_error);
        })

        MicroModal.show('modal-new-order');
        $('form.submit-order-product-search input[name="q"]').focus();
    })


    $(document).on('click', '.new-order__products-list .product .delete', function (e) {
        $(this).closest('tr').remove();
        recalculateTotals();
    })


    $(document).on('click', '#btn-order-print', function (e) {
        e.preventDefault();
        recalculateTotals();

        var discount = $('#new-order-discount').val().replace(/\D/g, '');

        $('#order-print tbody').html('')
        $('.new-order__products-list .product').each(function () {
            var $product = $(this);
            var $templateContent = $($('#print-new-order-item').html());
            var name = $product.find('td.name').text();
            var price = $product.find('input[name="price"]').val();
            var qty = $product.find('input[name="qty"]').val();

            $templateContent.find('td.name').html(name);
            $templateContent.find('td .price').html(price);
            $templateContent.find('td.qty').html(qty);

            $('#order-print tbody').append($templateContent);
        })

        if (discount > 0) {
            $('#order-print .print__total-wrapper .print__total').text(numberWithCommas(getTotal()));
            $('#order-print .print__total-wrapper').show();

            $('#order-print .print__discount-wrapper .print__discount').text(
                numberWithCommas(discount)
            );
            $('#order-print .print__discount-wrapper').show();
        } else {
            $('#order-print .print__discount-wrapper').hide();
            $('#order-print .print__total-wrapper').hide();
        }

        $('.print__paid').html($('.total-price').text());

        window.print();
    });

    $(document).on('click', '#submit-sell', function (e) {
        e.preventDefault();
        var $submitButton = $(this);
        var productsList = [];

        $('.new-order__products-list .product').each(function () {
            var $product = $(this);
            var price = $product.find('input[name="price"]').val();
            var qty = $product.find('input[name="qty"]').val();
            var id = $product.attr('data-id');

            productsList.push({
                id,
                qty,
                price
            })
        })

        var discount = $('#new-order-discount').val();
        var buyer_phone = $('input[name="buyer_phone"]').val();
        var create_user = +$('input[name="create_user"]')[0].checked;

        if (create_user && !buyer_phone) {
            alert(anbarak.i18n.phone_required_for_user);
            return;
        }

        $submitButton.attr("disabled", true).addClass('loading');

        $.ajax({
            method: 'POST',
            url: anbarak.ajax_url,
            data: {
                discount,
                buyer_name: $('input[name="buyer_name"]').val(),
                buyer_last_name: $('input[name="buyer_last_name"]').val(),
                buyer_address: $('input[name="buyer_address"]').val(),
                buyer_postal: $('input[name="buyer_postal"]').val(),
                buyer_province: $('select[name="buyer_province"]').val(),
                buyer_country: $('select[name="buyer_country"]').val() || '',
                customer_notes: $('textarea[name="customer_notes"]').val(),
                buyer_phone,
                buyer_email: $('input[name="buyer_email"]').val(),
                create_user,
                products: productsList,
	                action: 'anbarak_register_order',
                security: anbarak.nonce,
                nonce: anbarak.nonce,
                _nonce: anbarak.nonce,
                _ajax_nonce: anbarak.nonce,
            },
            dataType: "json"
        }).done(function (response) {
            $('#new-order-form')[0].reset();
            var phoneSelectx = $('.buyer-phone-selectx').data('selectx');
            if (phoneSelectx) phoneSelectx.clear();
            $('.new-order__products-list tbody').html('');
            $('.total-price').html('0');
            $submitButton.attr("disabled", false).removeClass('loading');
            $('#new-order-result').removeClass('d-none').fadeIn();
            setTimeout(function () {
                $('#new-order-result').fadeOut('');
            }, 5000)
        }).fail(function (response) {
            $submitButton.attr("disabled", false).removeClass('loading');
            alert(anbarak.i18n.order_creation_failed);
        })
    })
})(jQuery);
