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

export type returnResponse = {
	success: boolean;
	data: {
		pdf?: string;
		qr_code_data?: string;
		error?: string;
		qr_code_image_url?: string;
		bring_return_number?: string;
		link?: string;
	} };


export type UpdateReturnStep = (
	response: returnResponse,
	form: JQuery,
	step: number,
) => void;

export const updateReturnStep:UpdateReturnStep = (response, form, step) => {
	if ( response.success ) {
		const {i18n, return_carrier} = window.__wetail_shipping_return_portal;
		const isDataProvided = response.data.pdf || response.data.qr_code_data || response.data.qr_code_image_url || response.data.bring_return_number || response.data.link;

		if (response.data && isDataProvided) {
			const nextStep = form.parents( '.wetail-return-portal__step' ).siblings( '.wetail-return-portal__step--pdf' );

			if ((response.data.qr_code_data || response.data.qr_code_image_url) && (return_carrier === 'bring' || return_carrier === 'postnord')) {
				const url = response.data.qr_code_image_url ?? `data:image/png;base64,${response.data.qr_code_data}`;
				nextStep.find($('#wetail-return-portal__qr')).append($(`<img class="wetail-return-portal__qr--image ${response.data.qr_code_image_url ? 'wetail-return-portal__qr--image-url' : 'wetail-return-portal__qr--image-base64'}" src="${url}" alt="QR code" />`));
			}

			if (response.data.bring_return_number && return_carrier === 'bring') {
				nextStep.find($('#wetail-return-portal__qr')).remove();
				nextStep.find($('.wetail-return-portal__pdf-subtitle')).html(i18n.bring_return_number_message.replace('[bring_return_number]', response.data.bring_return_number))
			}

			if (response.data.link) {
				const stepElement = form.parents( '.wetail-return-portal__step' );
				stepElement.siblings( '.wetail-return-portal__step--pdf' )
					.find( $( '#print-label' ) )
					.attr( 'href', response.data.link  );
			}

			if (response.data.pdf) {
				const stepElement = form.parents( '.wetail-return-portal__step' );
				stepElement.siblings( '.wetail-return-portal__step--pdf' )
					.find( $( '#print-label' ) )
					.attr( 'href', response.data.pdf  );
			}

			goToStep( step + 1 );
		} else {
			console.error( '[WETAIL SHIPPING PORTAL] - return items step error, no pdf or data or qr_code_data provided' );
		}
	} else {
		if (response.data && response.data.error) {
			console.error( '[WETAIL SHIPPING PORTAL] - return items step error, response error: ', response.data.error );
			console.log( response );
		}
	}
}
