import $ from 'jquery';
import { get_carriers } from '../carriers/get_carriers';

export const fetch_and_display_carriers = 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( 'Carrier needs to be selected' );

	let carriers_response;
	try {
		carriers_response = await get_carriers( order_id );
	} catch ( _error ) {
		carriers_response = {
			error: true,
		};
	}

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

		const { data } = carriers_response;

		const wrapper = $( '<div class="carrier-select-wrapper"></div>' );

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

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

		if ( window._wetail_shipping.error_code === 'MAPPING_ERROR' ) {
			$( `<option value="" selected disabled>${ window._wetail_shipping.i18n[ 'Select carrier' ] }</option>` ).appendTo( select );
		} else {
			$( `<option value="use_mapping" selected>${ window._wetail_shipping.i18n[ 'Use mapping' ] }</option>` ).appendTo( select );
		}

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

		select.appendTo( wrapper );

		select.select2();

		$( wrapper ).appendTo( form );

		should_show_the_popup = true;

		form_heading = `
			${ window._wetail_shipping.i18n[ 'The order has no matching carrier mapping' ] }.<br>
			${ window._wetail_shipping.i18n[ 'Choose mapping below' ] } ${ window._wetail_shipping.i18n[ 'or' ] }
			<a class="edit-order-details" href="/wp-admin/admin.php?page=wc-orders&action=edit&id=${ order_id }">${ window._wetail_shipping.i18n[ 'edit order details' ] }</a><br>
			${ form_heading }
		`;

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

	return { should_show_the_popup, form_heading };
};
