/*
 * Amazon Field Mapping screen interactions – extracted from inline script.
 *
 * @package MOMCS_Sync
 */

/* global momcsAmazonFieldMapping, ajaxurl */

(function ($) {
	'use strict';

	const cfg = momcsAmazonFieldMapping || {};

	const {
		ajaxUrl,
		marketplaceId,
		channelUuid,
		nonces,
		wcAttributes,
		strings
	} = cfg;

	/**
	 * Build <option> list from WC attributes.
	 *
	 * @param {string} selected currently selected value
	 * @returns {string}
	 */
	const buildAttributeOptions = (selected = '') => {
		let html                = ` <option value = "" > ${strings.selectFieldPlaceholder} </option> `;
		$.each(
			wcAttributes,
			function (key, label) {
				const sel = key === selected ? ' selected' : '';
				html     += ` <option value = "${key}"${sel} > ${label} </option> `;
			}
		);
		return html;
	};

	/**
	 * Handle product-type change.
	 */
	const onProductTypeChange     = () => {
		const selectedProductType = $( '#momcs-field-mapping-product-type' ).val();

		if ( ! selectedProductType) {
			$( '#momcs-field-mapping-fields-container' ).hide();
			return;
		}

		$( '#momcs-field-mapping-fields-container' ).show();
		$( '.momcs-loading-message' ).show();
		$( '.momcs-field-mapping-table' ).hide();
		$( '#momcs-field-mapping-save' ).hide();
		$( '#momcs-field-mapping-rows' ).empty();

		$.post(
			ajaxUrl,
			{
				action: 'momcs_sync_get_product_type_schema',
				product_type: selectedProductType,
				marketplace_id: marketplaceId,
				channel_id: channelUuid,
				security: nonces.getSchema
			}
		).done(
			function (resp) {
				$( '.momcs-loading-message' ).hide();
				if ( ! resp.success || ! resp.data.required_fields) {
					$( '#momcs-field-mapping-rows' ).html( ` <tr> <td colspan = "4" class = "momcs-error" > ${strings.failedFetchFields} </td></tr> ` );
					$( '.momcs-field-mapping-table' ).show();
					return;
				}

				const requiredFields = resp.data.required_fields;
				if (Object.keys( requiredFields ).length === 0) {
					$( '#momcs-field-mapping-rows' ).html( ` <tr> <td colspan = "4" > ${strings.noRequiredFields} </td> </tr> ` );
					$( '.momcs-field-mapping-table' ).show();
					return;
				}

				// Fetch existing mapping
				$.post(
					ajaxUrl,
					{
						action: 'momcs_sync_get_field_mapping',
						marketplace: 'amazon',
						product_type: selectedProductType,
						security: nonces.getMapping
					}
				).done(
					function (mapResp) {
						const existing = (mapResp.success && mapResp.data.mappings) ? mapResp.data.mappings : {};
						buildRows( requiredFields, existing );
					}
				).fail(
					function () {
						buildRows( requiredFields, {} );
					}
				);
			}
		).fail(
			function () {
				$( '.momcs-loading-message' ).hide();
				$( '#momcs-field-mapping-rows' ).html( ` <tr> <td colspan = "4" class = "momcs-error" > ${strings.errorFetchFields} </td> </tr > ` );
				$( '.momcs-field-mapping-table' ).show();
			}
		);
	};

	/**
	 * Build table rows for required fields.
	 *
	 * @param {Object} requiredFields schema
	 * @param {Object} existingMappings pre-saved mapping
	 */
	const buildRows = (requiredFields, existingMappings) => {
		$.each(
			requiredFields,
			function (fieldName, fieldDetails) {
				const fieldType        = fieldDetails.type || 'string';
				const fieldDescription = fieldDetails.description || '';
				const selected         = existingMappings[fieldName] || '';

				const row = ` <tr class = "momcs-field-mapping-row" data - field = "${fieldName}" >
				<td class = "momcs-field-mapping-row-amazon-field" > ${fieldName} </td>
				<td> <select class = "momcs-field-mapping-row-wc-field" data - amazon - field = "${fieldName}" > ${buildAttributeOptions( selected )} </select> </td>
				<td> ${fieldType} </td>
				<td> ${fieldDescription} </td>
				</tr> `;
				$( '#momcs-field-mapping-rows' ).append( row );
			}
		);
		$( '.momcs-field-mapping-table' ).show();
		$( '#momcs-field-mapping-save' ).show();
	};

	/**
	 * Save mapping handler.
	 */
	const onSaveClick = function () {
		const $btn                = $( this );
		const $status             = $( '#momcs-field-mapping-status' );
		const selectedProductType = $( '#momcs-field-mapping-product-type' ).val();

		$btn.prop( 'disabled', true );
		$status.text( strings.saving ).removeClass().addClass( 'momcs-field-mapping-status momcs-field-mapping-status-saving' );

		const mappings = {};
		$( '.momcs-field-mapping-row' ).each(
			function () {
				const amazonField = $( this ).data( 'field' );
				const wcField     = $( this ).find( '.momcs-field-mapping-row-wc-field' ).val();
				if (amazonField && wcField) {
					mappings[amazonField] = wcField;
				}
			}
		);

		$.post(
			ajaxUrl,
			{
				action: 'momcs_sync_save_field_mapping',
				marketplace: 'amazon',
				product_type: selectedProductType,
				mapping_data: JSON.stringify( mappings ),
				security: nonces.saveMapping
			}
		).done(
			function (resp) {
				if (resp.success) {
					$status.html( ` <span class = "dashicons dashicons-yes-alt" > </span> ${strings.saved}` )
					.removeClass().addClass( 'momcs-field-mapping-status momcs-field-mapping-status-success' );
				} else {
					$status.html( ` <span class = "dashicons dashicons-warning" > </span> ${(resp.data && resp.data.message) || strings.failedSave}` )
					.removeClass().addClass( 'momcs-field-mapping-status momcs-field-mapping-status-error' );
				}
				$btn.prop( 'disabled', false );
			}
		).fail(
			function () {
				$status.html( ` <span class = "dashicons dashicons-warning" > </span > ${strings.failedSave}` )
				.removeClass().addClass( 'momcs-field-mapping-status momcs-field-mapping-status-error' );
				$btn.prop( 'disabled', false );
			}
		);
	};

	// Bind events
	$( '#momcs-field-mapping-product-type' ).on( 'change', onProductTypeChange );
	$( '#momcs-field-mapping-save' ).on( 'click', onSaveClick );

})( jQuery );
