(function ($) {
	'use strict';

	var cfg = window.rcInventory || {};

	function printUrl(inventoryId, opts) {
		opts = opts || {};
		var params = 'action=rc_print_inventory&id=' + inventoryId + '&_wpnonce=' + cfg.nonce;
		if (opts.hideBlank) params += '&hide_blank=1';
		if (opts.unemailed) params += '&unemailed=1';
		if ('supplier' in opts) params += '&supplier=' + encodeURIComponent(opts.supplier);
		return ajaxurl.replace('admin-ajax.php', 'admin-post.php') + '?' + params;
	}

	$(document).on('click', '.rc-order-inventory', function (e) {
		e.preventDefault();
		var inventoryId = $(this).data('id');
		openOrderModal(inventoryId);
	});

	$(document).on('click', '#rc-edit-areas-page', function (e) {
		e.preventDefault();
		var $frame = $('#rc-areas-page-frame');
		if (!$frame.attr('src')) {
			$frame.attr('src', $frame.data('src'));
		}
		$('#rc-areas-page-modal').prop('hidden', false);
	});

	$(document).on('click', '.rc-print-all', function (e) {
		e.preventDefault();
		var id = $(this).data('id');
		var hideBlank = $('#rc-print-hide-blank').is(':checked') ? 0 : 0;
		var url = printUrl(id, { hideBlank: true });
		window.open(url, '_blank');
	});

	$(document).on('click', '.rc-print-not-ordered', function (e) {
		e.preventDefault();
		var id = $(this).data('id');
		var url = printUrl(id, { hideBlank: true, unemailed: true });
		window.open(url, '_blank');
	});

	$(document).on('click', '.rc-print-supplier-btn', function (e) {
		e.stopPropagation();
		var id = $(this).data('inventory-id');
		var supplier = $(this).data('supplier');
		var url = printUrl(id, { hideBlank: true, supplier: supplier });
		window.open(url, '_blank');
	});

	function openOrderModal(inventoryId) {
		var $modal = $('#rc-order-modal');
		var $loading = $('#rc-order-loading');
		var $content = $('#rc-order-content');
		var $list = $('#rc-order-supplier-list');

		$('.rc-print-all').data('id', inventoryId);
		$('.rc-print-not-ordered').data('id', inventoryId);
		$loading.show();
		$content.hide();
		$list.empty();
		$modal.prop('hidden', false);

		$.getJSON(cfg.ajaxUrl, {
			action: 'rc_get_inventory_data',
			nonce: cfg.nonce,
			inventory_id: inventoryId
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$loading.text('Failed to load inventory data.');
				return;
			}
			renderOrderContent(resp.data, inventoryId, $list, $loading, $content);
		}).fail(function () {
			$loading.text('Request failed.');
		});
	}

	function renderOrderContent(data, inventoryId, $list, $loading, $content) {
		var items = (data.ingredients || []).concat(data.saved_items || []);
		var suppliers = {};
		var brickItems = [];

		$.each(items, function (_, item) {
			var supName = item.supplier_name || item.supplier || '';
			if ('' === supName) {
				brickItems.push(item);
				return;
			}
			if (!suppliers[supName]) {
				suppliers[supName] = { items: [], email_order: item.email_order || 0 };
			}
			suppliers[supName].items.push(item);
		});

		var html = '';
		var supKeys = Object.keys(suppliers).sort();

		$.each(supKeys, function (_, supName) {
			var group = suppliers[supName];
			var supItems = group.items;
			var emailOrder = group.email_order;
			var hasOrderable = false;
			var allEmailed = true;
			$.each(supItems, function (_, si) {
				if (parseFloat(si.order_qty) > 0) {
					hasOrderable = true;
					if (!parseInt(si.emailed)) {
						allEmailed = false;
					}
				}
			});

			html += '<div class="rc-supplier-group">';
			html += '<div class="rc-supplier-header">';
			html += '<span>' + $('<span>').text(supName).html() + '</span>';
			html += '</div>';
			html += '<div class="rc-supplier-items" style="display:none;">';
			html += '<table><thead><tr><th>Item</th><th>Qty</th><th>Min Level</th><th>Emailed</th></tr></thead><tbody>';
			$.each(supItems, function (_, si) {
				var emailedClass = parseInt(si.emailed) === 1 ? 'rc-ordered-row' : '';
				html += '<tr class="' + emailedClass + '">';
				html += '<td>' + $('<span>').text(si.ingredient_name || si.name || '').html() + '</td>';
				html += '<td>' + (parseFloat(si.order_qty) || 0) + '</td>';
				html += '<td>' + (parseInt(si.min_level) || 0) + '</td>';
				html += '<td>' + (parseInt(si.emailed) === 1 ? 'Yes' : 'No') + '</td>';
				html += '</tr>';
			});
			html += '</tbody></table>';
			html += '</div>';
			if (hasOrderable) {
				html += '<div class="rc-supplier-actions">';
				html += '<button type="button" class="button button-small btn-print-supplier rc-print-supplier-btn" data-inventory-id="' + inventoryId + '" data-supplier="' + $('<span>').text(supName).html() + '">Print ' + $('<span>').text(supName).html() + '</button>';
				if (emailOrder) {
					var label = allEmailed ? 'Resend Order' : 'Email ' + $('<span>').text(supName).html();
					var leaf = '<span class="dashicons dashicons-leaf"></span> ';
					html += '<button type="button" class="button button-small btn-email-supplier rc-send-order-btn" data-inventory-id="' + inventoryId + '" data-supplier="' + $('<span>').text(supName).html() + '">' + leaf + label + '</button>';
					if (allEmailed) {
						html += ' <span class="rc-emailed-msg">emailed. Marked ordered</span>';
					}
				}
				html += '</div>';
			}
			html += '</div>';
		});

		if (brickItems.length) {
			var hasBrickOrderable = false;
			$.each(brickItems, function (_, si) {
				if (parseFloat(si.order_qty) > 0) hasBrickOrderable = true;
			});
			html += '<div class="rc-supplier-group">';
			html += '<div class="rc-supplier-header">';
			html += '<span>No Supplier</span>';
			html += '</div>';
			html += '<div class="rc-supplier-items" style="display:none;">';
			html += '<table><thead><tr><th>Item</th><th>Qty</th><th>Min Level</th></tr></thead><tbody>';
			$.each(brickItems, function (_, si) {
				html += '<tr>';
				html += '<td>' + $('<span>').text(si.ingredient_name || si.name || '').html() + '</td>';
				html += '<td>' + (parseFloat(si.order_qty) || 0) + '</td>';
				html += '<td>' + (parseInt(si.min_level) || 0) + '</td>';
				html += '</tr>';
			});
			html += '</tbody></table>';
			html += '</div>';
			if (hasBrickOrderable) {
				html += '<div class="rc-supplier-actions">';
				html += '<button type="button" class="button button-small btn-print-supplier rc-print-supplier-btn" data-inventory-id="' + inventoryId + '" data-supplier="">Print No Supplier</button>';
				html += '</div>';
			}
			html += '</div>';
		}

		$list.html(html);
		$loading.hide();
		$content.show();

		$('.rc-supplier-header').off('click').on('click', function () {
			$(this).next('.rc-supplier-items').slideToggle();
		});
	}

	$(document).on('click', '.rc-send-order-btn', function (e) {
		e.stopPropagation();
		var $btn = $(this);
		var inventoryId = $btn.data('inventory-id');
		var supplierName = $btn.data('supplier');

		var clickCount = parseInt($btn.data('click-count') || 0);

		if (clickCount > 0) {
			var $prompt = $(
				'<div class="rc-prompt-overlay"><div class="rc-prompt-box">' +
				'<p>Email Already Sent. Send again??</p>' +
				'<p class="rc-prompt-buttons">' +
				'<button type="button" class="button rc-prompt-no">NO, Don\'t send</button> ' +
				'<button type="button" class="button button-primary rc-prompt-yes">Yes, Send Again</button>' +
				'</p></div></div>'
			);
			$('body').append($prompt);

			$prompt.find('.rc-prompt-yes').on('click', function () {
				$prompt.remove();
				$btn.data('click-count', clickCount + 1);
				sendOrderEmail($btn, inventoryId, supplierName);
			});
			$prompt.find('.rc-prompt-no').on('click', function () {
				$prompt.remove();
			});
			$prompt.on('click', function (e) {
				if ($(e.target).hasClass('rc-prompt-overlay')) {
					$prompt.remove();
				}
			});
			return;
		}

		$btn.data('click-count', clickCount + 1);
		sendOrderEmail($btn, inventoryId, supplierName);
	});

	function sendOrderEmail($btn, inventoryId, supplierName) {
		$btn.prop('disabled', true);
		var originalText = $btn.html();
		$btn.html('Sending...');

		$.post(cfg.ajaxUrl, {
			action: 'rc_send_order_email',
			nonce: cfg.nonce,
			inventory_id: inventoryId,
			supplier_name: supplierName
		}).done(function (resp) {
			if (resp && resp.success) {
				var $list = $('#rc-order-supplier-list');
				var $loading = $('#rc-order-loading');
				var $content = $('#rc-order-content');
				$.getJSON(cfg.ajaxUrl, {
					action: 'rc_get_inventory_data',
					nonce: cfg.nonce,
					inventory_id: inventoryId
				}).done(function (resp2) {
					if (resp2 && resp2.success) {
						renderOrderContent(resp2.data, inventoryId, $list, $loading, $content);
					}
				});
			} else {
				$('#rc-order-loading').text((resp && resp.data && resp.data.message) || 'Failed to send order.').show();
				$btn.prop('disabled', false).html(originalText);
			}
		}).fail(function () {
			$('#rc-order-loading').text('Request failed.').show();
			$btn.prop('disabled', false).html(originalText);
		});
	}

	$(document).on('click', '.rc-modal-backdrop, .rc-modal-close, .rc-modal-cancel', function () {
		$(this).closest('.rc-modal').prop('hidden', true);
	});

	$(document).on('keydown', function (e) {
		if (e.key === 'Escape') {
			$('.rc-modal:not([hidden])').prop('hidden', true);
		}
	});

	$(document).on('click', '#rc-add-area-btn', function () {
		$('#rc-area-modal-form')[0].reset();
		$('#rc-area-id').val('');
		$('#rc-area-add-new').val('');
		$('#rc-area-modal-title').text('Add Area');
		$('#rc-area-modal').prop('hidden', false);
		$('#rc-area-name').trigger('focus');
	});

	$(document).on('click', '.rc-edit-area', function () {
		var id = $(this).data('id');
		var name = $(this).data('name');
		$('#rc-area-modal-form')[0].reset();
		$('#rc-area-id').val(id);
		$('#rc-area-add-new').val('');
		$('#rc-area-name').val(name);
		$('#rc-area-modal-title').text('Edit Area');
		$('#rc-area-modal').prop('hidden', false);
		$('#rc-area-name').trigger('focus');
	});

	$(document).on('click', '.rc-save-add', function (e) {
		e.preventDefault();
		$('#rc-area-add-new').val('1');
		$('#rc-area-modal-form').submit();
	});

})(jQuery);
