import { debounce, formatPriceElement, tippyUpdateTemplate, isFormChanged } from './utils.js';

; (function ($) {
	if ($('.app-content.inventory').length < 1) return;

	const $productListTable = $('.anbarak-products-wrapper-table-wrapper');
	const $productSearchForm = $('form.product-search');
	const $clearFormButton = $('button.clear-form');
	let page = 1;
	let perPage = 0;
	let currentFormSerializedData = '';

	const refreshFormattedFields = function () {
		$('.thousand-separator').each(function () {
			formatPriceElement($(this));
		});
	};

	const toggleClearButton = function () {
		if (isFormChanged($productSearchForm[0])) {
			$clearFormButton.removeClass('hidden');
		} else {
			$clearFormButton.addClass('hidden');
		}
	};

	const resetSearchForm = function () {
		$productSearchForm[0].reset();
		toggleClearButton();
	};

	const updateSearchResults = function () {
		let itemsPerPage;
		let ajaxData;

		const serializedSearchForm = $productSearchForm.serialize();
		ajaxData = serializedSearchForm;

		itemsPerPage = $('#ipp').val();

		if (!perPage) {
			perPage = itemsPerPage;
		}

		// reset pagination if filter form changed
		if (ajaxData == currentFormSerializedData || !currentFormSerializedData) {
			if (itemsPerPage) {
				ajaxData += '&ipp=' + itemsPerPage;
			}
			if (perPage == itemsPerPage) {
				if (page && page > 1) {
					ajaxData += '&paged=' + page;
				}
			}
		}

		currentFormSerializedData = serializedSearchForm;

		perPage = itemsPerPage;

		$productListTable.parent().block();

		$.ajax({
			method: 'GET',
			url: anbarak.ajax_url,
			data: ajaxData,
			dataType: 'html'
		}).done(function (html) {
			$productListTable.find('.product-item').remove();
			$productListTable.html(html);

			refreshFormattedFields();

			setTimeout(function () {
				$productListTable.parent().unblock();
			}, 80);
		}).fail(function (response) {
			$productListTable.parent().unblock();
		});

		toggleClearButton();
	};

	$(document).ready(function () {
		function liveSearch(e) {
			const search = $productSearchForm.find('input[name="q"]').val();
			let toSearch;
			const regex = new RegExp(search);

			if (!search) {
				$productListTable.find('tr.product-item').show(200);
			} else {
				const filter = $productSearchForm.find('select[name="t"]').val();

				$productListTable.find('tr.product-item')
					.hide(0)
					.filter(function () {
						toSearch = $(this).data('title');
						if ('p-stock' == filter) {
							return search == $(this).find('input[name="stock"]').val();
						}
						if ('p-sku' == filter) {
							return $(this).find('input[name="sku"][value^="' + search + '"]').val();
							// return search == $(this).find('input[name="sku"][]').val();
						}
						return regex.test(toSearch)
					})
					.show(200);
			}
		}

		$productSearchForm.find('input[name="q"]').on('keyup', debounce(function (e) {
			liveSearch(e);
		}, 400));

		$productSearchForm.find('select').on('change', function (e) {
			liveSearch(e);
		});

		$productSearchForm.on('submit', function (e) {
			e.preventDefault();
			updateSearchResults();
		});

		$('.stock-nav button').on('click', function (e) {
			e.preventDefault();
			$('.stock-nav button').removeClass('active');
			$(this).addClass('active');
			$(this).next('input').prop('checked', true);
			updateSearchResults();
		});

		$('#stock-view-select').on('change', function () {
			const selectedValue = $(this).val();
			$('input[name="view"]').prop('checked', false);
			$('input[name="view"][value="' + selectedValue + '"]').prop('checked', true);

			updateSearchResults();
		});

		$('#group-variables-switch').on('change', function () {
			updateSearchResults();
		});

		$(document).on('click', 'button.search-by-title', function (e) {
			e.preventDefault();
			resetSearchForm();
			$('input[name="q"]').val($(this).data('title'));
			updateSearchResults();
		});

		$(document).on('click', 'button.clear-form', function (e) {
			e.preventDefault();
			$clearFormButton.addClass('hidden');
			if (isFormChanged($productSearchForm[0])) {
				$productSearchForm[0].reset();
				updateSearchResults();
			}
		});

		$(document).on('keydown', function (e) {
			if (e.key === 'Escape') {
				if ($('.micro-modal.is-open').length === 0) {
					e.preventDefault();
					if (isFormChanged($productSearchForm[0])) {
						$productSearchForm[0].reset();
						updateSearchResults();
					}
				}
			}
		});

		$(document).on('click', 'button.btn-submit-save', function (e) {
			e.preventDefault();

			var $button = $(this);
			var $tr = $button.closest('tr');
			var productId = $tr.data('id');
			var variation = $tr.find('input[name="var_id"]').val();
			var price = $tr.find('input[name="price"]').val();
			var salePrice = $tr.find('input[name="sale_price"]').val();
			var buyPrice = $tr.find('input[name="buy_price"]').val();
			var stock = $tr.find('input[name="stock"]').val();
			var stockInitial = $tr.find('input[name="stock-initial"]').val();
			var online_sell = $tr.find('select[name="online-sell"]').val();
			var backorders = $tr.find('select[name="backorders"]').val();
			var sku = $tr.find('input[name="sku"]').val();
			var weight = $tr.find('input[name="weight"]').val();

			$button.addClass('loading');
			$button.prop('disabled', true);

			$.ajax({
				method: 'POST',
				url: anbarak.ajax_url,
				data: {
					pid: productId,
					variation: variation,
					price: price,
					sale_price: salePrice,
					buy_price: buyPrice,
					stock_change: stock - stockInitial,
					sku: sku,
					weight: weight,
					online_sell: online_sell,
					backorders: backorders,
						action: 'anbarak_product_save',
					security: anbarak.nonce
				},
				dataType: 'json'
			}).done(function (response) {
				$tr.find('input[name="stock-initial"]').val(response.qty);
				// the product stock may changed when purchasing on shop
				// so update its value to user to see the current stock
				$tr.find('input[name="stock"]').val(response.qty);
				$tr.find('.anbarak-qty-sync-warning .qty-diff').text(response.qty - response.anbarak_qty);
				$tr.find('.anbarak-qty-sync-warning .anbarak-qty').text(response.anbarak_qty);
				if (response.qty <= response.anbarak_qty) {
					$tr.find('.anbarak-qty-sync-warning').hide();
				} else {
					$tr.find('.anbarak-qty-sync-warning').show();
				}

				tippyUpdateTemplate();

				$button.prop('disabled', false);
				$button.removeClass('loading');

				$tr.addClass('product-row-update-highlight');
				setTimeout(() => {
					$tr.removeClass('product-row-update-highlight');
				}, 2000);
			}).fail(function (jqXHR) {
				$tr.addClass('highlight--red');
				$button.prop('disabled', false);
				$button.removeClass('loading');

				if (jqXHR.responseJSON && !jqXHR.responseJSON.success) {
					anbarakConfirm({
						title: anbarak.i18n.error_saving_product,
						message: jqXHR.responseJSON.data,
						okText: anbarak.i18n.understood,
						onClose: function () {
							$tr.removeClass('highlight--red');
						}
					});
				} else {
					alert(anbarak.i18n.request_failed + ' ' + jqXHR.status + ' ' + jqXHR.statusText);
				}

			});
		});


		$(document).on('click', '#manage-columns', function (e) {
			e.preventDefault();
			MicroModal.show('modal-columns');
		});


		$('#modal-1').keypress(function (e) {
			if (e.keyCode == $.ui.keyCode.ENTER) {
				registerProductBuyExpense($('#submit-purchase'));
			}
		});


		$(document).on('change', '#ipp', function (e) {
			updateSearchResults();
		});

		$(document).on('click', '.pagination a', function (e) {
			e.preventDefault();
			page = parseInt($(this).text(), 10) || 1;
			updateSearchResults();
		});

		$(document).on('click', '#confirm-columns', function (e) {
			e.preventDefault();
			const $form = $('#form-manage-columns');

			$.ajax({
				method: 'POST',
				url: anbarak.ajax_url,
				data: $form.serialize(),
				dataType: 'html'
			}).done(function (html) {
				updateSearchResults();
				MicroModal.close('modal-columns');
			});
		});
	});


	$('.search-form-wrapper select[name="t"]').on('change', function () {
		const placeholder = $(this).find('option:selected').data('input-placeholder');
		const selectedValue = $(this).val();
		$(this).parents('form').find('input[name="q"]').attr('placeholder', placeholder);
		localStorage.setItem('anbarak_submit_order_search_method', selectedValue);
	});

	const savedMethod = localStorage.getItem('anbarak_submit_order_search_method');
	if (savedMethod) {
		$('.search-form-wrapper select[name="t"]').val(savedMethod).trigger('change');
	}

})(jQuery);
