import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

const normalizeSiteData = ( data: any ) => {
	// Restructure sites as object and key to be site domain
	return data.reduce( ( acc: any, site: any ) => {
		acc[ site.domain ] = site;
		return acc;
	}, {} );
};

const fetchLianaMailerData = async ( apiUrl: string, endpoint: string ) => {
	const sitesPath = apiUrl.replace( ':endpoint', endpoint );
	const result = await apiFetch( {
		url: sitesPath,
	} );

	return result;
};

const getSiteOptions = ( lianaMailerData ) => {
	if ( ! lianaMailerData ) {
		return [ { label: __( 'No sites found', 'liana-with-growthstack' ), value: '' } ];
	}
	const options = Object.keys( lianaMailerData ).map( ( domain ) => ( {
		label: domain,
		value: domain,
	} ) );
	options.unshift( {
		label: __( 'Select a site', 'liana-with-growthstack' ),
		value: '',
	} );
	return options;
};

const getPropertyOptions = ( { formStateSettings, lianaMailerData } ) => {
	const defaultProperties = [
		{
			label: __( 'Select a field', 'liana-with-growthstack' ),
			value: '',
		},
		{ label: __( 'Email', 'liana-with-growthstack' ), value: 'email' },
		{ label: __( 'SMS', 'liana-with-growthstack' ), value: 'sms' },
		{
			label: __( 'Mailing Lists', 'liana-with-growthstack' ),
			value: 'lianamailer_mailinglists',
		},
	];
	const siteData = lianaMailerData?.[ formStateSettings?.site ];
	if ( ! siteData || ! siteData.properties || ! siteData.properties.length ) {
		return defaultProperties;
	}
	const options = siteData.properties.map( ( property ) => ( {
		label: property.name,
		value: property.name,
	} ) );
	return [ ...defaultProperties, ...options ];
};

const fetchSettings = async ( endpoint: string ) => {
	try {
		const response = await apiFetch( {
			url: endpoint,
			method: 'GET',
		} );
		if ( response.success && response.data && response.data.lianamailer ) {
			return response.data.lianamailer;
		}
		return null;
	} catch ( error: any ) {
		return null;
	}
};

const sendBatchToggle = ( endpoint: string, forms: Array< any > ) => {
	try {
		const response = apiFetch( {
			url: endpoint,
			method: 'PATCH',
			headers: {
				'Content-Type': 'application/json',
			},
			body: JSON.stringify( {
				action: 'batchToggle',
				forms,
			} ),
			keepalive: true,
		} );

		return response;
	} catch ( error ) {
		return null;
	}
};

type LianaMailerSettings = {
	site?: string;
	lists?: string;
	properties?: Record< string, string >;
};

const isLianaMailerConfigured = ( settings: LianaMailerSettings ) => {
	if ( ! settings?.site || ! settings?.lists?.length ) {
		return false;
	}

	// Check if properties have email mapped
	const emailMapped = Object.values( settings?.properties || {} ).includes(
		'email'
	);
	if ( ! emailMapped ) {
		return false;
	}

	return true;
};

export {
	fetchLianaMailerData,
	fetchSettings,
	getSiteOptions,
	getPropertyOptions,
	isLianaMailerConfigured,
	normalizeSiteData,
	sendBatchToggle,
};
