/**
 * widgetCommentsCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller("widgetCommentsCtrl", [
	"$scope",
	"Comment",
	"CommentsService",
	"ErrorsHandler",
	"$interval",
	"$ClientsManager",
	"$uibModal",
	function (
		$scope,
		Comment,
		CommentsService,
		ErrorsHandler,
		$interval,
		$ClientsManager,
		$uibModal
	) {
		/**
		 * Comments
		 *
		 * @type array
		 */
		$scope.comments = CommentsService.comments;
		$scope.pages = CommentsService.pages;
		/**
		 * Object storing data properties..
		 *
		 * @type Object
		 */
		$scope.options = {};

		/**
		 * Indicate if send comment is in process
		 *
		 * @type boolean
		 */
		$scope.sending = false;

		/**
		 * Stores a new comment.
		 *
		 * @return void
		 */
		$scope.addComment = function (data) {
			$scope.sending = true;

			var data = {
				related_id: $scope.data.id,
				related_type: $scope.type,
				message: $scope.comment,
				public: $scope.public,
				send_email: $scope.options.send_email,
				email: $scope.options.email,
				cc: $scope.options.cc,
				created_by: $scope.user
			};

			CommentsService.addComment(data).then(function (response) {
				$scope.comment = "";
				$scope.sending = false;
				$scope.public = false;
				$scope.pages = CommentsService.pages;
				$scope.currentPage = CommentsService.currentPage;
			});
		};

		/**
		 * Watches for when the task is fully loaded.
		 *
		 * @return void
		 */
		$scope.$watch("data.id", function (value) {
			if (value) {
				CommentsService.loadComments(
					{
						related_type: $scope.type,
						related_id: $scope.data.id
					},
					function name(params) {
						$scope.pages = CommentsService.pages;
						$scope.currentPage = CommentsService.currentPage;
					}
				);
			}
		});
		$scope.keyDownEvent = $event => {
			if ($event.ctrlKey && $event.keyCode === 13) {
				$scope.addComment($event);
			}
		};
		/**
		 * Watch for when the email address changes.
		 *
		 * @return void
		 */
		var emailWatcher = $scope.$watch(
			function () {
				return $ClientsManager.data;
			},
			function (data) {
				if (data.email && !$scope.email) {
					//if NHS auto mark public
					if (
						data.email == "imandtservicedesk@ouh.nhs.uk" ||
						data.email == "imandtservicedeskadmin@ouh.nhs.uk"
					) {
						$scope.public = true;
						$scope.options.send_email = true;
					}
					$scope.options.email = data.email;
					emailWatcher(); // de-register the $watch
				}
			},
			true
		);

		/**
		 * Loads all the comments for this particular task.
		 *
		 * @return void
		 */
		$scope.loadComments = function (current_page, append) {
			$scope.currentPage = current_page;
			Comment.get(
				{
					type: $scope.type,
					id: $scope.data.id,
					page: current_page
				},
				function (res) {
					if (append) {
						// Append new comments to existing ones
						CommentsService.comments = CommentsService.comments.concat(res.data);
					} else {
						// Replace comments
						CommentsService.comments = [];
						CommentsService.setComments(res.data, res.last_page);
					}
					$scope.comments = CommentsService.comments;
					$scope.pages = res.last_page;
				},
				ErrorsHandler
			);
		};

		/**
		 * Show email customer modal
		 *
		 * @return void
		 */
		$scope.showEmailCustomerModal = function () {
			if (!$scope.data || !$scope.data.id || $scope.type !== 'task') {
				return;
			}

			// Get customer email from client data
			var customerEmail = $ClientsManager.data && $ClientsManager.data.email ? $ClientsManager.data.email : '';
			if (!customerEmail) {
				if (typeof Messenger !== 'undefined') {
					Messenger("Cannot email customer: No customer email found");
				}
				return;
			}

			var modalInstance = $uibModal.open({
				templateUrl: 'bookings/modals/email-customer.html',
				controller: 'EmailCustomerModalCtrl',
				size: 'lg',
				resolve: {
					data: function () {
						return {
							id: $scope.data.id,
							title: $scope.data.title,
							client_name: $ClientsManager.data.name || $ClientsManager.data.Name || ''
						};
					},
					customerEmail: function () {
						return customerEmail;
					}
				}
			});

			modalInstance.result.then(function (result) {
				// Success notification is already shown in the modal controller
				// Reload comments to show the email notification
				CommentsService.loadComments({
					related_type: $scope.type,
					related_id: $scope.data.id
				});
			}, function () {
				// Modal dismissed
			});
		};

		/**
		 * Generate mailto URL for customer email (kept for backward compatibility)
		 *
		 * @return string
		 */
		$scope.getMailtoUrl = function () {
			// Instead of opening mailto, show the email modal
			return '#';
		};

		/**
		 * Delete a comment
		 *
		 * @return void
		 */
		$scope.deleteComment = function (comment) {
			if (!confirm('Are you sure you want to delete this comment? This action cannot be undone.')) {
				return;
			}

			Comment.delete(
				{ commentId: comment.id },
				function (res) {
					// Remove from the comments array by finding the comment with matching ID
					// Note: $scope.comments and CommentsService.comments reference the same array,
					// so we only need to splice once
					var index = CommentsService.comments.findIndex(function(c) { return c.id === comment.id; });

					if (index !== -1) {
						CommentsService.comments.splice(index, 1);
					}

					if (typeof Messenger !== 'undefined') {
						Messenger('Comment deleted successfully');
					}
				},
				function (error) {
					if (typeof Messenger !== 'undefined') {
						Messenger('Failed to delete comment');
					}
					ErrorsHandler(error);
				}
			);
		};

		/**
		 * Autorefresh the comments every 1 minute
		 *
		 * @return void
		 */
		var cancelRefresh = $interval(function myFunction() {
			CommentsService.loadComments({
				related_type: $scope.type,
				related_id: $scope.data.id
			});
		}, 300 * 1000); // 1 minute(s) refresh
	}
]);
