/**
 * Init the tec.ticket_plus.waitlistClassic object.
 */

tec.tickets_plus = tec.tickets_plus || {};

tec.tickets_plus.waitlistClassic = tec.tickets_plus.waitlistClassic || {};

( ($, obj) => {
	const $document = $( document );

	/**
	 * Selectors used to attach listeners.
	 *
	 * @since 6.2.0
	 * @type {Object}
	 */
	obj.selectors = {
		editScreen: '.tec-tickets-plus-waitlist-metabox__create-container',
		mainScreen: '.tec-tickets-plus-waitlist-metabox__overview',
		cancelEdit: '.tec-tickets-plus-waitlist-metabox__save-cancel',
		addWaitlist: '.tec-tickets-plus-waitlist-metabox__add-ticket',
		editWaitlist: '.tec-tickets-plus-waitlist-metabox__edit',
		deleteWaitlist: '.tec-tickets-plus-waitlist-metabox__delete',
		saveWaitlist: '.tec-tickets-plus-waitlist-metabox__save-waitlist',
		waitlistIdInEditScreen: 'input[name="waitlist_id"]',
		conditionalTicketInEditScreen: 'input[name="ticket-conditional"]:checked',
		conditionalRSVPInEditScreen: 'input[name="rsvp-conditional"]:checked',
		nonceInEditScreen: 'input[name="nonce"]',
		deleteNonce: 'input[name="tec-tickets-plus-waitlist-metabox-delete-nonce"]',
		parent: '#tec-tickets-plus-waitlist-metabox .inside',
	};

	/**
	 * I18n strings.
	 *
	 * @since 6.2.0
	 * @type {Object}
	 */
	obj.i18n = {
		confirmDelete: wp.i18n.__( 'Are you sure you want to delete this waitlist? This will also delete all the subscribers of this waitlist!', 'event-tickets-plus' ),
	};

	/**
	 * Close the edit screen.
	 *
	 * @since 6.2.0
	 * @param {Event} e
	 */
	obj.closeEditScreen = ( e ) => {
		e.preventDefault();

		const target = $( e.target );

		target.closest( obj.selectors.editScreen ).hide();
		$document.find( obj.selectors.mainScreen ).show();
	};

	/**
	 * Open the edit screen.
	 *
	 * @since 6.2.0
	 * @param {Event} e
	 */
	obj.openEditScreen = ( e ) => {
		e.preventDefault();

		const target = $( e.target );

		const type = target.data( 'type' ) || target.closest( obj.selectors.editWaitlist ).data( 'type' );

		target.closest( obj.selectors.mainScreen ).hide();
		$document.find( obj.selectors.editScreen + '[data-type="' + type+ '"]' ).show();
	};

	/**
	 * Delete a waitlist.
	 *
	 * @since 6.2.0
	 * @param {Event} e
	 */
	obj.deleteWaitlist = async ( e ) => {
		e.preventDefault();

		const target = $( e.target );
		const waitlist_id = target.data( 'waitlist-id' ) || target.closest( obj.selectors.deleteWaitlist ).data( 'waitlist-id' );
		const nonce = $document.find( obj.selectors.deleteNonce ).val();

		if ( ! ( waitlist_id && nonce ) ) {
			return;
		}

		if ( ! confirm( obj.i18n.confirmDelete ) ) {
			return;
		}

		// Save the waitlist.
		const formData = new FormData();
		formData.append( 'action', 'tec_tickets_plus_waitlist_delete' );
		formData.append( 'nonce', nonce );
		formData.append( 'waitlist_id', waitlist_id );

		target.prop( 'disabled', true );

		const response = await fetch( TribeTicketsPlus.ajaxurl, {
			method: 'POST',
			body: formData,
		} );

		target.prop( 'disabled', false );

		if (!response.ok) {
			throw new Error( 'Failed to submit waitlist form.' );
		}

		const json = await response.json();

		if ( ! json?.success ) {
			console.error( 'Failed to submit waitlist form.', json );
			return false;
		}

		$document.find( obj.selectors.parent ).html( json.data.markup );
	};

	obj.saveWaitlist = async ( e ) => {
		e.preventDefault();

		const target = $( e.target );
		const editScreen = target.closest( obj.selectors.editScreen );

		if ( ! editScreen.length ) {
			return;
		}

		const waitlistId = editScreen.find( obj.selectors.waitlistIdInEditScreen ).val();
		const type = target.data( 'type' );
		const conditional = 'ticket' === type ?
			editScreen.find( obj.selectors.conditionalTicketInEditScreen ).val() :
			editScreen.find( obj.selectors.conditionalRSVPInEditScreen ).val();
		const nonce = editScreen.find( obj.selectors.nonceInEditScreen ).val();

		if ( ! ( conditional && nonce ) ) {
			return;
		}

		// Save the waitlist.
		const formData = new FormData();
		formData.append( 'action', 'tec_tickets_plus_waitlist_save' );
		formData.append( 'nonce', nonce );
		formData.append( 'waitlist_id', waitlistId );
		formData.append( 'conditional', conditional );
		formData.append( 'post_id', $("#post_ID").val() );
		formData.append( 'type', 'ticket' === type ? 0 : 1 );

		target.prop( 'disabled', true );

		const response = await fetch( TribeTicketsPlus.ajaxurl, {
			method: 'POST',
			body: formData,
		} );

		target.prop( 'disabled', false );

		if (!response.ok) {
			throw new Error( 'Failed to submit waitlist form.' );
		}

		const json = await response.json();

		if ( ! json?.success ) {
			console.error( 'Failed to submit waitlist form.', json );
			return false;
		}

		$document.find( obj.selectors.parent ).html( json.data.markup );
	};

	/**
	 * Ready function.
	 *
	 * @since 6.2.0
	 * @type {Function}
	 */
	obj.ready = () => {
		$document.on( 'click', obj.selectors.cancelEdit, obj.closeEditScreen );
		$document.on( 'click', obj.selectors.addWaitlist, obj.openEditScreen );
		$document.on( 'click', obj.selectors.editWaitlist, obj.openEditScreen );
		$document.on( 'click', obj.selectors.deleteWaitlist, obj.deleteWaitlist );
		$document.on( 'click', obj.selectors.saveWaitlist, obj.saveWaitlist );
	};

	$( obj.ready );
})( jQuery, tec.tickets_plus.waitlistClassic );
