import $ from 'jquery';
import { get_pickup_time } from './pickup_time';
import { get_selected_sender_id } from './selected_sender';
import { get_selected_carrier_id } from '../carriers/selected_carrier';
import { fetch_and_display_carriers } from './fetch_and_display_carriers';
import { fetch_and_display_senders } from './fetch_and_display_senders';
import { display_pickup_details } from './display_pickup_details';
import { initialize_shipping_modal } from './initialize_shipping_modal';


export const show_form_with_senders_select_and_datepicker = async (
	order_id: string,
	has_multiple_senders: boolean,
	book_pickup_manually: boolean,
	enable_manual_shipping_service_selection_override: boolean,
) => {
	let should_show_the_popup: boolean = false;

	const selected_carrier_id: string | undefined = get_selected_carrier_id( order_id );
	const selected_sender_id: string | undefined = get_selected_sender_id( order_id );
	const pickup_time: string | undefined = get_pickup_time( order_id );

	if ( has_multiple_senders && selected_sender_id && book_pickup_manually && pickup_time && !enable_manual_shipping_service_selection_override ) {
		return should_show_the_popup;
	}

	if ( !book_pickup_manually && has_multiple_senders && selected_sender_id && !enable_manual_shipping_service_selection_override ) {
		return should_show_the_popup;
	}

	if ( !has_multiple_senders && book_pickup_manually && pickup_time && !enable_manual_shipping_service_selection_override ) {
		return should_show_the_popup;
	}

	const form = $( '<form class="sender-and-pickup-form"></form>' );
	form.attr( 'data-order_id', order_id );

	let form_heading = '';

	if ( enable_manual_shipping_service_selection_override && !selected_carrier_id ) {
		const result = await fetch_and_display_carriers( order_id, form, should_show_the_popup, form_heading );
		should_show_the_popup = result.should_show_the_popup;
		form_heading = result.form_heading;
	}

	if ( has_multiple_senders && !selected_sender_id ) {
		const result = await fetch_and_display_senders( order_id, form, should_show_the_popup, form_heading );
		should_show_the_popup = result.should_show_the_popup;
		form_heading = result.form_heading;
	}

	if ( book_pickup_manually && !pickup_time ) {
		const result = display_pickup_details( has_multiple_senders, selected_sender_id, form, should_show_the_popup, form_heading );
		should_show_the_popup = result.should_show_the_popup;
		form_heading = result.form_heading;
	}

	$( `<p>${ form_heading }</p>` ).prependTo( form );

	if ( should_show_the_popup ) {
		initialize_shipping_modal( order_id, form );
	}

	return should_show_the_popup;
};
