(function($) {
	'use strict';

	function readExpirationValue($cell) {
		var $target = $cell.find('[data-expiration]');
		if (!$target.length) {
			return '';
		}
		var value = $target.attr('data-expiration');
		return value == null ? '' : String(value);
	}

	function formatDisplay(value) {
		if (!value) {
			return '—';
		}
		var normalized = String(value).replace('T', ' ');
		var parts = normalized.split(' ');
		if (parts.length < 2) {
			return value;
		}
		var dateParts = parts[0].split('-');
		var timeParts = parts[1].split(':');
		if (dateParts.length < 3 || timeParts.length < 2) {
			return value;
		}
		var month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
		var hour = parseInt(timeParts[0], 10);
		var minute = timeParts[1];
		var ampm = hour >= 12 ? 'pm' : 'am';
		var hour12 = hour % 12;
		if (hour12 === 0) {
			hour12 = 12;
		}
		return month[parseInt(dateParts[1], 10) - 1] + ' ' + parseInt(dateParts[2], 10) + ', ' + dateParts[0] +
			' ' + hour12 + ':' + minute + ' ' + ampm;
	}

	function updateListCell(postId, value) {
		var $row = $('#post-' + postId);
		var $cell = $('td.column-wpps_expiration', $row);
		if (!$cell.length) {
			return;
		}

		if (!value) {
			$cell.html('<span class="wpps-expiration-empty" data-expiration="">—</span>');
			return;
		}

		$cell.html(
			'<span class="wpps-expiration-value" data-expiration="' +
			$('<div>').text(value).html() +
			'">' +
			$('<div>').text(formatDisplay(value)).html() +
			'</span>'
		);
	}

	function parseRequestData(data) {
		if (!data) {
			return null;
		}

		if (typeof data === 'string') {
			return new URLSearchParams(data);
		}

		if (typeof data === 'object') {
			var params = new URLSearchParams();
			Object.keys(data).forEach(function(key) {
				var value = data[key];
				if (value == null) {
					return;
				}
				if (Array.isArray(value)) {
					value.forEach(function(item) {
						params.append(key, String(item));
					});
					return;
				}
				params.append(key, String(value));
			});
			return params;
		}

		return null;
	}

	function initQuickEdit() {
		if (typeof inlineEditPost === 'undefined') {
			return;
		}

		var originalEdit = inlineEditPost.edit;
		inlineEditPost.edit = function(id) {
			originalEdit.apply(this, arguments);

			if (typeof id === 'object') {
				id = this.getId(id);
			}

			var editRow = $('#edit-' + id);
			var postRow = $('#post-' + id);

			if (!editRow.length || !postRow.length) {
				return;
			}

			var expirationValue = readExpirationValue($('td.column-wpps_expiration', postRow));
			$('input[name="wpps_expiration_date"]', editRow).val(expirationValue);
		};

		if (inlineEditPost._wppsSavePatched) {
			return;
		}
		inlineEditPost._wppsSavePatched = true;

		var originalSave = inlineEditPost.save;
		inlineEditPost.save = function(id) {
			if (typeof id === 'object') {
				id = this.getId(id);
			}

			var postId = id;
			var expirationValue = String($('#edit-' + postId).find('input[name="wpps_expiration_date"]').val() || '');
			var jqPost = $.post;

			$.post = function(url, params, callback, type) {
				if (typeof params === 'string' && params.indexOf('action=inline-save') !== -1) {
					return jqPost.call($, url, params, function(response) {
						if (typeof callback === 'function') {
							callback(response);
						}
						if (response && String(response).indexOf('<tr') !== -1) {
							updateListCell(postId, expirationValue);
						}
					}, type);
				}

				return jqPost.apply($, arguments);
			};

			try {
				return originalSave.apply(this, arguments);
			} finally {
				$.post = jqPost;
			}
		};
	}

	if (window.inlineEditPost) {
		initQuickEdit();
	} else {
		$(initQuickEdit);
	}

	$(document).ajaxSuccess(function(event, xhr, settings) {
		if (!settings.data) {
			return;
		}

		var params = parseRequestData(settings.data);
		if (!params || params.get('action') !== 'inline-save') {
			return;
		}

		var postId = parseInt(params.get('post_ID'), 10);
		if (!postId) {
			return;
		}

		updateListCell(postId, params.get('wpps_expiration_date') || '');
	});

	$(document).on('input change', '#bulk-edit input[name="wpps_expiration_date"]', function() {
		$('#bulk-edit input[name="wpps_expiration_update"]').prop('checked', String(this.value || '') !== '');
	});
})(jQuery);
