/**
 * All admin-facing JavaScript for the plugin.
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/admin/assets/js
 * @author     Edu Brazeal <contact@edubrazeal.com>
 *
 * Note: This script depends on the 'wp-media' script. We will need to ensure
 * it is enqueued as a dependency in our PHP class that loads this script.
 */

(function ($) {
	'use strict';

	$(document).ready(function () {

		var mediaFrame;
		var imagePreviewTemplate = $('#aitnb-asset-preview-image-template').html();
		var textPreviewTemplate = $('#aitnb-asset-preview-text-template').html();
		var consentCheckbox = $('#aitnb_api_data_consent');
		var i18n = aitnb_admin_params.i18n;

		function toggleApiButtonsState() {
			var isConsented = consentCheckbox.is(':checked');
			$('.aitnb-test-api-button, #aitnb-fetch-models-btn').prop('disabled', !isConsented);
		}

		toggleApiButtonsState();

		consentCheckbox.on('change', toggleApiButtonsState);

		$(document).off('click', '.aitnb-upload-asset-button').on('click', '.aitnb-upload-asset-button', function (e) {
			e.preventDefault();

			if (mediaFrame) {
				mediaFrame.open();
				return;
			}

			mediaFrame = wp.media({
				title: 'Select or Upload Try-On Asset',
				button: {
					text: 'Use this asset'
				},
				multiple: false
			});

			mediaFrame.on('select', function () {
				var attachment = mediaFrame.state().get('selection').first().toJSON();
				var previewHtml = '';

				$('#aitnb_overlay_asset_id').val(attachment.id);

				if (attachment.sizes && attachment.sizes.thumbnail) {
					var $imagePreview = $(imagePreviewTemplate);
					$imagePreview.attr('src', attachment.sizes.thumbnail.url);
					previewHtml = $imagePreview;
				} else {
					var $textPreview = $(textPreviewTemplate);
					$textPreview.find('.aitnb-asset-filename').text(attachment.filename);
					previewHtml = $textPreview;
				}

				$('.aitnb-asset-preview').html(previewHtml);

				$('.aitnb-remove-asset-button').show();
			});

			mediaFrame.open();
		});

		$(document).off('click', '.aitnb-remove-asset-button').on('click', '.aitnb-remove-asset-button', function (e) {
			e.preventDefault();

			$('#aitnb_overlay_asset_id').val('');

			$('.aitnb-asset-preview').html('');

			$(this).hide();
		});

		$(document).off('click', '.aitnb-test-api-button').on('click', '.aitnb-test-api-button', function(e) {
			e.preventDefault();

			var $button = $(this);
			var apiType = $button.data('api');
			var $apiKeyField = $('#aitnb_' + (apiType === 'google_vision' ? 'google' : 'gemini') + '_api_key');
			var apiKey = $apiKeyField.val();
			var $spinner = $button.siblings('.spinner');
			var $result = $button.siblings('.aitnb-api-test-result');

			$result.text('').removeClass('success error');
			$spinner.addClass('is-active');
			$button.prop('disabled', true);

			if (!apiKey) {
				$result.text(i18n.apiKeyMissing).addClass('error');
				$spinner.removeClass('is-active');
				toggleApiButtonsState();
				return;
			}

			var ajaxData = {
				action: 'aitnb_test_api_connection',
				nonce: aitnb_admin_params.nonce,
				api_type: apiType,
				api_key: apiKey
			};

			if (apiType === 'gemini') {
				ajaxData.model_name = $('#aitnb_gemini_fit_model').val();
			}

			$.ajax({
				url: aitnb_admin_params.ajax_url,
				type: 'POST',
				data: ajaxData,
				success: function (response) {
					if (response.success) {
						$result.text(response.data.message).addClass('success');
					} else {
						var errorMessage = response.data && response.data.message ? response.data.message : i18n.errorPrefix + 'Unknown error';
						$result.text(errorMessage).addClass('error');
					}
				},
				error: function () {
					$result.text(i18n.requestFailed).addClass('error');
				},
				complete: function () {
					$spinner.removeClass('is-active');
					toggleApiButtonsState();
				}
			});
		});

		$(document).off('click', '#aitnb-fetch-models-btn').on('click', '#aitnb-fetch-models-btn', function(e) {
			e.preventDefault();

			var $button = $(this);
			var $apiKeyField = $('#aitnb_gemini_api_key');
			var apiKey = $apiKeyField.val();
			var $spinner = $('#aitnb-fetch-spinner');
			var $result = $('#aitnb-fetch-result');
			var $fitSelect = $('#aitnb_gemini_fit_model');
			var $styleSelect = $('#aitnb_gemini_style_model');

			$result.text('').removeClass('success error');
			$spinner.addClass('is-active');
			$button.prop('disabled', true);

			if (!apiKey) {
				$result.text(i18n.geminiApiKeyMissing).addClass('error');
				$spinner.removeClass('is-active');
				toggleApiButtonsState();
				return;
			}

			$.ajax({
				url: aitnb_admin_params.ajax_url,
				type: 'POST',
				data: {
					action: 'aitnb_fetch_gemini_models',
					nonce: aitnb_admin_params.nonce,
					api_key: apiKey
				},
				success: function (response) {
					if (response.success) {
						$result.text(i18n.modelsFetchedSuccess).addClass('success');

						var currentFitModel = $fitSelect.val();
						var currentStyleModel = $styleSelect.val();

						$fitSelect.empty().append($('<option></option>').attr('value', '').text('-- Select a Model --'));
						$styleSelect.empty().append($('<option></option>').attr('value', '').text('-- Select a Model --'));

						if (response.data && response.data.models && Array.isArray(response.data.models)) {
							$.each(response.data.models, function(index, model) {
								if (model && model.id && model.name) {
									var option = $('<option></option>').attr('value', model.id).text(model.name);
									$fitSelect.append(option.clone());
									$styleSelect.append(option.clone());
								}
							});
						}

						$fitSelect.val(currentFitModel);
						$styleSelect.val(currentStyleModel);

					} else {
						var errorMessage = response.data && response.data.message ? response.data.message : i18n.errorPrefix + 'Unknown error';
						$result.text(errorMessage).addClass('error');
					}
				},
				error: function () {
					$result.text(i18n.requestFailed).addClass('error');
				},
				complete: function () {
					$spinner.removeClass('is-active');
					toggleApiButtonsState();
				}
			});
		});
	});

})(jQuery);