import { isObject, mapValues } from 'lodash';
import {
	LocationResponse,
	OriginAddress,
	RateExtraOptions,
	ShipmentRecord,
	WCShippingAnalyticsConfig,
	WCShippingConfig,
	WCShippingConfigAccountSettings,
} from 'types';
import { camelCaseKeys, composeAddress, composeName } from 'utils';

export const getConfig = (): WCShippingConfig =>
	( window.WCShipping_Config || {} ) as WCShippingConfig;

export const getWeightUnit = () => {
	return getConfig().shippingLabelData.storeOptions.weight_unit;
};

export const getCurrencySymbol = () => {
	return getConfig().shippingLabelData.storeOptions.currency_symbol;
};

export const getDimensionsUnit = () => {
	return getConfig().shippingLabelData.storeOptions.dimension_unit;
};

export const getAccountSettings = ( { accountSettings } = getConfig() ) =>
	accountSettings;

export const setAccountSettings = (
	newSettings: WCShippingConfigAccountSettings
) => {
	getConfig().accountSettings = newSettings;
};

export const getLastOrderCompleted = ( { accountSettings } = getConfig() ) =>
	accountSettings.userMeta.last_order_completed;

export const getSelectedRates = () =>
	getConfig().shippingLabelData.storedData.selected_rates;

export const getSelectedHazmat = () =>
	getConfig().shippingLabelData.storedData.selected_hazmat;

export const getCustomsInformation = () =>
	getConfig().shippingLabelData.storedData.customs_information;

export const getStoredPackageDimensions = () => {
	const config = getConfig();
	return config?.shippingLabelData?.storedData?.package_dimensions;
};

export const getPluginRelativeDirectory = ( forWooCommerce = false ) =>
	forWooCommerce
		? getConfig().constants.WC_PLUGIN_RELATIVE_DIR
		: getConfig().constants.WCSHIPPING_RELATIVE_PLUGIN_DIR;

export const shouldAutomaticallyOpenPrintDialog = ( config = getConfig() ) =>
	getAccountSettings( config ).purchaseSettings
		.automatically_open_print_dialog;

// Only set on Analytics page
export const getAnalyticsConfig = () =>
	window.WCShipping_Config as WCShippingAnalyticsConfig;

export const getSelectedRateOptions = (
	config = getConfig()
): ShipmentRecord< RateExtraOptions > => {
	const selectedRates = config.shippingLabelData.storedData.selected_rates;
	if ( isObject( selectedRates ) ) {
		return mapValues( selectedRates, ( { extra_options } ) =>
			camelCaseKeys( extra_options )
		);
	}
	return {};
};

export const getCustomFulfillmentSummary = (
	{ custom_fulfillment_summary } = getConfig()
) => custom_fulfillment_summary;

export const getShipmentsAutogeneratedFromLabels = (
	{ shipments_autogenerated_from_labels } = getConfig()
) => shipments_autogenerated_from_labels;

export const getPromotion = () => {
	const promo = getConfig().promotion;
	if ( promo?.remaining === 0 ) {
		return null;
	}
	return promo;
};

export const shouldUseFulfillmentApi = (
	{ should_use_fulfillment_api } = getConfig()
) => should_use_fulfillment_api;

export const isMainOriginInSyncWithStore = (
	{ is_main_origin_in_sync_with_store } = getConfig()
) => is_main_origin_in_sync_with_store ?? false;

export const getFormattedStoreAddress = (
	{ formatted_store_address } = getConfig()
) => formatted_store_address ?? '';

/**
 * Convert a snake_case LocationResponse to a camelCase OriginAddress.
 */
export const normalizeStoreAddressDraft = (
	draft: LocationResponse
): OriginAddress => ( {
	id: draft.id,
	city: draft.city,
	email: draft.email,
	firstName: draft.first_name,
	lastName: draft.last_name,
	phone: draft.phone,
	postcode: draft.postcode,
	state: draft.state,
	country: draft.country,
	address1: draft.address_1 ?? '',
	address2: draft.address_2 ?? '',
	address: composeAddress( draft ),
	name: composeName( draft ),
	company: draft.company,
	isVerified: draft.is_verified,
	defaultAddress: draft.default_address,
	defaultReturnAddress: draft.default_return_address,
	isApproved: draft.is_approved,
} );

export const getStoreAddressDraft = (
	{ store_address_draft } = getConfig()
): OriginAddress | undefined => {
	if ( ! store_address_draft ) {
		return undefined;
	}

	return normalizeStoreAddressDraft( store_address_draft );
};
