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

export const fetch_and_display_senders = async ( order_id: string, form: JQuery<HTMLElement>, should_show_the_popup: boolean, form_heading: string ): Promise<{
	should_show_the_popup: boolean
	form_heading: string
}> => {
	console.info( 'Sender needs to be selected' );

	form_heading += ' ' + window._wetail_shipping.i18n[ 'Please' ] + ' ' + window._wetail_shipping.i18n[ 'select a shipping sender' ];

	const senders_response = await get_senders( order_id );

	if ( senders_response && !senders_response.error && senders_response.data && Array.isArray( senders_response.data ) ) {

		const { data } = senders_response;

		$( `<label for="selected-sender">${ window._wetail_shipping.i18n[ 'Sender' ] }</label>` ).appendTo( form );

		const select = $( '<select class="sender-and-pickup-form__select" name="selected-sender" id="selected-sender" required></select>' );

		$( `<option value="" disabled selected>${ window._wetail_shipping.i18n[ 'Choose sender' ] }</option>` ).appendTo( select );

		data.forEach( ( sender ) => {
			const option = $( '<option></option>' );
			option.attr( 'value', sender.id.toString() );
			option.text( sender.name );
			option.appendTo( select );
		} );

		select.appendTo( form );

		select.select2();

		should_show_the_popup = true;

	} else if ( !senders_response ) {
		console.error( 'No senders response' );
	} else if ( senders_response.error ) {
		console.error( 'Senders response error:', senders_response.message );
	} else if ( !senders_response.data ) {
		console.error( 'Senders response doesn\'t have "data" property' );
	} else if ( !Array.isArray( senders_response.data ) ) {
		console.error( 'Senders response "data" property is not an array' );
	}

	return { should_show_the_popup, form_heading };
};
