import $ from 'jquery';
import { getOrderItems } from './getOrderItems';
import { goToStep } from './goToStep';
import { updateReturnStep } from './updateReturnStep';

type DataType = {
	action: 'wetail_shipping_portal',
	do: string,
	nonce: string,
	order_password: string,
	order_number: number,
	order_items: any[],
	qr_code_to_phonenumber?: string,
}


export const returnItemsStep = ( form: JQuery, step: number ) => {
	const items = form.find( $( '.order-item' ) );

	if ( items.length === 0 ) {
		return;
	}

	if (!window.__wetail_shipping_return_portal.order_password) {
		console.error( '[WETAIL SHIPPING PORTAL] - order_password is not defined' );
		return;
	}

	const order_items = getOrderItems( items );

	if ( order_items.length === 0 ) {
		alert( 'Please select at least one item.' );
		return;
	}

	if ( window.__wetail_shipping_return_portal.order_number === 0 ) {
		console.error( '[WETAIL SHIPPING PORTAL] - order id not set correctly in js' );
		return;
	}

	const verificationForm = $('.wetail-return-portal__step--order-verification form')
	const qr_code_to_phonenumber = verificationForm.find( $( '#qr_code_to_phonenumber' ) );
	const { return_carrier, order_number, order_password, nonce, ajaxurl } = window.__wetail_shipping_return_portal;
	const spinner = form.find( $( 'button .spinner' ) );

	const data: DataType = {
		action: 'wetail_shipping_portal',
		do: 'order_return_items',
		nonce,
		order_password: '',
		order_number: 0,
		order_items
	};

	if ( typeof order_password === 'string' && order_password.replace( /\s/g, '' ) !== '' ) {
		data.order_password = order_password;
	}

	if ( typeof order_number !== 'undefined' ) {
		data.order_number = order_number;
	}

	if ( return_carrier === 'postnord' || return_carrier === 'bring' ) {
		data[ 'qr_code_to_phonenumber' ] = qr_code_to_phonenumber.val() as string;
	}

	spinner.fadeIn( 200 );

	$.post( ajaxurl, data )
		.done( response => {
			if ( response.success ) {
				updateReturnStep( response, form, step );
			} else {
				console.error( '[WETAIL SHIPPING PORTAL] - return items step error, response error: ', response.data.error );
			}
		} )
		.fail( ( response ) => {
			console.error( '[WETAIL SHIPPING PORTAL] - return items step error: ' + response.responseText );
		} )
		.always( () => {
			spinner.fadeOut( 200 );
		} );


};
