jQuery(function($) {
	var customerPricing = window.b2bking_customer_pricing || {};

	function setting(key, fallback) {
		if (typeof customerPricing[key] !== 'undefined') {
			return customerPricing[key];
		}
		if (typeof window.b2bking !== 'undefined' && typeof window.b2bking[key] !== 'undefined') {
			return window.b2bking[key];
		}
		return fallback || '';
	}

	function escapeHtml(text) {
		return $('<div>').text(text || '').html();
	}

	function decodeHtml(text) {
		return $('<textarea>').html(text || '').text();
	}

	function loadCrmPricing($wrap, page) {
		if (!$wrap.length) { return; }
		$wrap.data('b2bking-loaded', true);
		var $table = $wrap.find('.b2bking-customer-pricing-table');
		$table.html('<div class="b2bking-crm-empty-state">Loading...</div>');
		$.post(ajaxurl, {
			action: 'b2bking_crm_pricing_products',
			security: setting('security'),
			user_id: $wrap.data('user-id'),
			search: $wrap.find('.b2bking-customer-pricing-search').val(),
			page: page || 1
		}, function(response) {
			$table.html(response.success ? response.data.html : '<div class="b2bking-crm-empty-state">' + setting('error', 'Error') + '</div>').data('page', page || 1);
			initPricingTooltips($table);
		});
	}

	function initPricingTooltips($scope) {
		if (typeof tippy !== 'function') { return; }
		($scope || $(document)).find('.b2bking-customer-pricing-tip').each(function() {
			if (this._tippy) { return; }
			tippy(this, {
				animation: 'shift-away',
				allowHTML: true,
				theme: 'material'
			});
		});
	}

	function initCrmPricing($scope) {
		($scope || $(document)).find('.b2bking-customer-pricing').each(function() {
			var $wrap = $(this);
			if (!$wrap.data('b2bking-loaded')) {
				loadCrmPricing($wrap, 1);
			}
		});
	}

	if (window.location.search.indexOf('b2bking_update_existing=1') !== -1) {
		$('#woocommerce-importer-update-existing').prop('checked', true);
	}

	initCrmPricing($(document));
	$(document).on('b2bking_crm_panel_loaded b2bking_crm_tab_changed', function() {
		initCrmPricing($(document));
	});

	$(document).on('click', '.b2bking-customer-pricing-import-export-toggle', function() {
		$(this).closest('.b2bking-customer-pricing').find('.b2bking-customer-pricing-import-export-panel').first().slideToggle(150);
	});

	$(document).on('click', '.b2bking-customer-pricing-search-btn', function() {
		loadCrmPricing($(this).closest('.b2bking-customer-pricing'), 1);
	});

	$(document).on('input', '.b2bking-customer-pricing-search', function() {
		var $input = $(this);
		clearTimeout($input.data('b2bking-search-timer'));
		$input.data('b2bking-search-timer', setTimeout(function() {
			loadCrmPricing($input.closest('.b2bking-customer-pricing'), 1);
		}, 350));
	});

	$(document).on('keypress', '.b2bking-customer-pricing-search', function(e) {
		if (e.which === 13) {
			e.preventDefault();
			loadCrmPricing($(this).closest('.b2bking-customer-pricing'), 1);
		}
	});

	$(document).on('click', '.b2bking-customer-pricing-page', function() {
		loadCrmPricing($(this).closest('.b2bking-customer-pricing'), $(this).data('page'));
	});

	$(document).on('click', '.b2bking-customer-price-save', function() {
		var $row = $(this).closest('[data-product-id][data-user-id]');
		var $status = $row.find('.b2bking-customer-price-status');
		saveCustomerPrice($row, $status, false, $(this));
	});

	$(document).on('click', '.b2bking-customer-price-clear', function() {
		var $row = $(this).closest('[data-product-id][data-user-id]');
		var $status = $row.find('.b2bking-customer-price-status');
		$row.find('.b2bking-customer-regular, .b2bking-customer-sale').val('');
		saveCustomerPrice($row, $status).done(function(response) {
			if (response.success && !getTiers($row).length) {
				$row.next('.b2bking-customer-pricing-tiers-row').remove();
				$row.remove();
			} else if (response.success && $row.closest('.b2bking-customer-pricing-editor').length) {
				$row.next('.b2bking-customer-pricing-tiers-row').slideDown(120);
			}
		});
	});

	$(document).on('click', '.b2bking-customer-pricing-tiers-toggle', function() {
		var $panel = $(this).closest('[data-product-id][data-user-id]').next('.b2bking-customer-pricing-tiers-row');
		if (!$panel.find('.b2bking-customer-pricing-tier').length) {
			$panel.find('.b2bking-customer-pricing-tier-list').append(tierRowHtml('', ''));
		}
		$panel.slideToggle(120);
	});

	$(document).on('click', '.b2bking-customer-tier-add', function() {
		var $panel = $(this).closest('.b2bking-customer-pricing-tiers-row');
		$panel.find('.b2bking-customer-pricing-tier-list').append(tierRowHtml('', ''));
		updateTierButton($panel.prev('[data-product-id][data-user-id]'));
	});

	$(document).on('click', '.b2bking-customer-tier-remove', function() {
		var $panel = $(this).closest('.b2bking-customer-pricing-tiers-row');
		$(this).closest('.b2bking-customer-pricing-tier').remove();
		updateTierButton($panel.prev('[data-product-id][data-user-id]'));
	});

	$(document).on('input', '.b2bking-customer-tier-quantity, .b2bking-customer-tier-price', function() {
		updateTierButton($(this).closest('.b2bking-customer-pricing-tiers-row').prev('[data-product-id][data-user-id]'));
	});

	$(document).on('click', '.b2bking-customer-pricing-save-all', function() {
		var $button = $(this);
		var $table = $button.closest('.b2bking-customer-pricing-table');
		var $rows = $table.find('.b2bking-customer-pricing-row[data-product-id][data-user-id]');
		var $status = $table.find('.b2bking-customer-pricing-save-all-status');
		if (!$rows.length) { return; }
		$button.prop('disabled', true);
		$status.text(setting('saving', 'Saving...')).show();
		var requests = $rows.map(function() {
			return saveCustomerPrice($(this), $(this).find('.b2bking-customer-price-status'), true);
		}).get();
		$.when.apply($, requests).always(function() {
			$button.prop('disabled', false);
			$status.text(setting('saved', 'Saved')).fadeIn().delay(1500).fadeOut();
		});
	});

	$(document).on('click', '.b2bking-product-customer-prices-save-all', function() {
		var $button = $(this);
		var $modal = $(this).closest('.b2bking-product-pricing-modal');
		var $rows = $modal.find('.b2bking-product-pricing-row[data-product-id][data-user-id]');
		var $status = $modal.find('.b2bking-product-customer-prices-save-all-status');
		if (!$rows.length) { return; }
		$button.prop('disabled', true);
		$status.text(setting('saving', 'Saving...')).show();
		var requests = $rows.map(function() {
			return saveCustomerPrice($(this), $(this).find('.b2bking-customer-price-status'), true);
		}).get();
		$.when.apply($, requests).always(function() {
			$button.prop('disabled', false);
			$status.text(setting('saved', 'Saved')).fadeIn().delay(1500).fadeOut();
		});
	});

	function saveCustomerPrice($row, $status, quiet, $button) {
		return $.post(ajaxurl, {
			action: $row.closest('.b2bking-product-pricing-modal').length ? 'b2bking_product_customer_price_save' : 'b2bking_crm_pricing_save',
			security: setting('security'),
			product_id: $row.data('product-id'),
			user_id: $row.data('user-id'),
			regular: $row.find('.b2bking-customer-regular').val(),
			sale: $row.find('.b2bking-customer-sale').val(),
			tiers_present: 1,
			tiers: getTiers($row)
		}, function(response) {
			updateTierButton($row);
			if (!quiet) {
				if ($button) {
					$button.hide();
				}
				$status.text(response.success ? setting('saved', 'Saved') : setting('error', 'Error')).fadeIn().delay(1500).fadeOut(function() {
					if ($button) {
						$button.show();
					}
				});
			}
		});
	}

	function getTiers($row) {
		var tiers = [];
		$row.next('.b2bking-customer-pricing-tiers-row').find('.b2bking-customer-pricing-tier').each(function() {
			var quantity = $(this).find('.b2bking-customer-tier-quantity').val();
			var price = $(this).find('.b2bking-customer-tier-price').val();
			if (quantity !== '' && price !== '') {
				tiers.push({ quantity: quantity, price: price });
			}
		});
		return tiers;
	}

	function updateTierButton($row) {
		var count = getTiers($row).length;
		$row.find('.b2bking-customer-pricing-tiers-toggle').text(count ? 'Tiers (' + count + ')' : 'Tiers');
	}

	function tierRowHtml(quantity, price) {
		return '<div class="b2bking-customer-pricing-tier">' +
			'<input type="number" step="any" min="0" class="b2bking-customer-tier-quantity" value="' + escapeHtml(quantity) + '">' +
			'<input type="text" class="b2bking-customer-tier-price wc_input_price" value="' + escapeHtml(price) + '">' +
			'<button type="button" class="button button-small b2bking-customer-tier-remove">&times;</button></div>';
	}

	function tiersPanelHtml() {
		return '<div class="b2bking-customer-pricing-tiers-row" style="display:none;">' +
			'<div class="b2bking-customer-pricing-tiers">' +
			'<div class="b2bking-customer-pricing-tier-head"><span>Min. Quantity</span><span>' + escapeHtml(decodeHtml(customerPricing.tier_value_label || 'Price')) + '</span><span></span></div>' +
			'<div class="b2bking-customer-pricing-tier-list"></div>' +
			'<button type="button" class="button button-small b2bking-customer-tier-add">Add Tier</button>' +
			'</div></div>';
	}

	$(document).on('click', '.b2bking-product-customer-prices', function() {
		if (typeof Swal === 'undefined') { return; }
		var productId = $(this).data('product-id');
		Swal.fire({
			width: 760,
			padding: 0,
			showCloseButton: true,
			showConfirmButton: false,
			customClass: { popup: 'b2bking-crm-swal-popup', closeButton: 'b2bking-crm-close-btn' },
			didOpen: function() {
				Swal.showLoading();
				$.post(ajaxurl, { action: 'b2bking_product_customer_prices', security: setting('security'), product_id: productId }, function(response) {
					Swal.update({ html: response.success ? response.data.html : setting('error', 'Error') });
					Swal.hideLoading();
					initUserSearch();
				});
			}
		});
	});

	function initUserSearch() {
		var $select = $('.b2bking-customer-price-user-search');
		if (!$select.length || !$select.select2) { return; }
		$select.select2({
			placeholder: setting('type_to_search_users', 'Type to search users...'),
			minimumInputLength: 3,
			width: '100%',
			dropdownParent: $('.swal2-popup'),
			ajax: {
				url: ajaxurl,
				dataType: 'json',
				delay: 250,
				data: function(params) {
					return { action: 'b2bking_admin_user_search', security: setting('security'), search: params.term };
				},
				processResults: function(data) {
					if (!data.success) { return { results: [] }; }
					return {
						results: data.data.map(function(item) {
							return { id: item.id, text: item.text };
						})
					};
				}
			}
		}).on('select2:select', function(e) {
			var productId = $('.b2bking-product-pricing-modal').data('product-id');
			var userId = e.params.data.id;
			if ($('.b2bking-product-pricing-row[data-user-id="' + userId + '"]').length) { return; }
			$('.b2bking-product-pricing-rows .b2bking-crm-empty-state').remove();
			var row = 
				'<div class="b2bking-product-pricing-row" data-product-id="' + productId + '" data-user-id="' + userId + '">' +
				'<span>' + escapeHtml(e.params.data.text) + '</span>' +
				'<input type="text" class="b2bking-customer-regular short wc_input_price">' +
				'<input type="text" class="b2bking-customer-sale short wc_input_price">' +
				'<span class="b2bking-customer-pricing-actions"><button type="button" class="button button-small b2bking-customer-pricing-tiers-toggle">Tiers</button><button type="button" class="button button-small b2bking-customer-price-save">Save</button>' +
				'<button type="button" class="button button-small b2bking-customer-price-clear" title="' + escapeHtml(customerPricing.remove_prices || 'Remove prices') + '" aria-label="' + escapeHtml(customerPricing.remove_prices || 'Remove prices') + '">&times;</button>' +
				'<span class="b2bking-customer-price-status"></span></span></div>';
			$('.b2bking-product-pricing-head').after(row + tiersPanelHtml());
			$select.val(null).trigger('change');
		});
	}
});
