import $ from 'jquery';
import { getErrors } from '../form/getErrors';
import { showError } from '../form/showError';
import { verifyOrder } from './verifyOrder';

export const orderVerificationStep = ( form: JQuery<HTMLFormElement>, step: number ) => {
	const errors = getErrors( form );

	$( '.wetail-return-portal__form-field' ).removeClass( 'invalid' );

	if ( errors && errors.length > 0 ) {
		errors.forEach( errorSelector => $( errorSelector ).parents( '.wetail-return-portal__form-field' ).addClass( 'invalid' ) );
		return;
	}

	const order_number = form.find( $( '#order-number' ) ).val() as string;
	const order_email = form.find( $( '#order-email' ) ).val() as string;

	/**
	 * Set order id to window for later access
	 */
	window.__wetail_shipping_return_portal.order_number = parseInt( order_number );

	const spinner = form.find( $( 'button .spinner' ) );

	spinner.fadeIn( 200 );

	return $.post( window.__wetail_shipping_return_portal.ajaxurl, {
		action: 'wetail_shipping_portal',
		do: 'order_verification',
		nonce: window.__wetail_shipping_return_portal.nonce,
		order_number,
		order_email,
	} )
		.done( ( response ) => {
			verifyOrder( response, step, form );
		} )
		.fail( () => {
			console.error( '[WETAIL SHIPPING PORTAL] - order verification step error, failed request' );
			showError( form );
		} )
		.always( () => {
			spinner.fadeOut( 200 );
		} );
};
