import $ from 'jquery';
import { validateEmail } from './validateEmail';
import { isValidSwedishPhone } from './isValidSwedishPhone';
import { addErrorToWrapper } from './addErrorToWrapper';

export const getErrors = ( form: JQuery ) => {
	const allInputs = form.find( 'input' );
	const errorWrapper = $( '.wetail-return-portal__error' );
	const { i18n } = window.__wetail_shipping_return_portal;

	errorWrapper.empty();

	let errors: string[] = [];

	allInputs.each( ( _, element ) => {
		const _this = $( element );
		const id = _this.prop( 'id' );
		const label = _this.siblings( 'label' );
		const labelText = label.text();
		const value = _this.val() as string;
		const trimmedValue = value.trim();
		const isEmpty = trimmedValue === '';

		if ( isEmpty ) {
			errors.push( `#${ id }` );
			addErrorToWrapper( `.wetail-return-portal__error--msg-empty-field-${id}`, i18n.field_empty_error.replace( '[field]', `"${labelText}"` ) );
		}

		if ( !isEmpty && id === 'order-email' && !validateEmail( value ) ) {
			errors.push( `#${ id }` );
			addErrorToWrapper( '.wetail-return-portal__error--msg-email', i18n.email_error );
		}

		if ( !isEmpty && id === 'qr_code_to_phonenumber' && !isValidSwedishPhone( value ) ) {
			errors.push( `#${ id }` );
			addErrorToWrapper( '.wetail-return-portal__error--msg-phone', i18n.phone_error );
		}
	} );

	if (errors.length === 0) {
		errorWrapper.hide();
	}

	if ( errors.length > 0 ) {
		errorWrapper.fadeIn( 200 );
	}

	return errors;
};
