// External dependencies.
import React, { ReactElement, useEffect } from 'react';

// WordPress dependencies
import { __ } from '@wordpress/i18n';

// Divi dependencies.
import {
	AdminLabelGroup,
	FieldContainer,
} from '@divi/module';
import { GroupContainer } from '@divi/modal';
import {
	TextContainer,
	SelectContainer,
	ToggleContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { ApplyButtonAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getEffectiveAttrValue,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

declare global {
	interface Window {
		JSFDiviViews: any;
	}
}

const getAvailableProviders = () => {
	const providers = window.JSFDiviViews?.providers || {};
	return convertObjectOptions(providers);
}

const APPLY_BUTTON_DEFAULTS_FALLBACK: Record<string, any> = {
	content_provider: 'not-selected',
	apply_type: 'ajax',
	apply_button_text: __( 'Apply filter', 'jet-engine-divi-views' ),
	apply_redirect: false,
	redirect_path: '',
	active_state: 'always',
	if_inactive: 'disable',
	query_id: '',
	additional_providers_enabled: false,
	additional_providers_list: [
		{
			additional_provider: '',
			additional_providers_list: '',
		},
	],
};

const APPLY_BUTTON_SELECT_ATTRS = new Set( [
	'content_provider',
	'apply_type',
	'active_state',
	'if_inactive',
] );

const APPLY_BUTTON_TOGGLE_ATTRS = new Set( [
	'apply_redirect',
	'additional_providers_enabled',
] );

export const SettingsContent = (props: Module.Settings.Panel.Props<ApplyButtonAttrs>): ReactElement => {
	const {
		defaultSettingsAttrs,
		attrs,
	} = props;
	const setAttrs = (
		(props as unknown as { setAttrs?: (next: Partial<ApplyButtonAttrs>) => void; setAttributes?: (next: Partial<ApplyButtonAttrs>) => void }).setAttrs
		|| (props as unknown as { setAttributes?: (next: Partial<ApplyButtonAttrs>) => void; onChange?: (next: Partial<ApplyButtonAttrs>) => void }).setAttributes
		|| (props as unknown as { onChange?: (next: Partial<ApplyButtonAttrs>) => void }).onChange
	);
	const applyButtonDefaults = APPLY_BUTTON_DEFAULTS_FALLBACK;

	useEffect( () => {
		if ( ! setAttrs ) {
			return;
		}

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: applyButtonDefaults,
			toggleKeys: APPLY_BUTTON_TOGGLE_ATTRS,
			selectKeys: APPLY_BUTTON_SELECT_ATTRS,
		} );

		if ( Object.keys( next ).length ) {
			setAttrs( next );
		}
	}, [ attrs, setAttrs, applyButtonDefaults ] );

	const getToggleDefaultAttr = ( key: string ) => buildDefaultInnerContent( {
		key,
		value: applyButtonDefaults[ key ],
		toggleKeys: APPLY_BUTTON_TOGGLE_ATTRS,
		selectKeys: APPLY_BUTTON_SELECT_ATTRS,
	} );

	const getValue = ( key: string ) => getEffectiveAttrValue( {
		attrs,
		key,
		defaults: applyButtonDefaults,
		toggleKeys: APPLY_BUTTON_TOGGLE_ATTRS,
		selectKeys: APPLY_BUTTON_SELECT_ATTRS,
	} );

	const applyRedirect = isToggleEnabledValue( getValue( 'apply_redirect' ) );
	const activeState = getValue( 'active_state' );

	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="content_provider.innerContent"
				label={__('This filter for', 'jet-engine-divi-views')}
				description=""
			>
				<SelectContainer options={getAvailableProviders()} />
			</FieldContainer>

			<FieldContainer
				attrName="apply_type.innerContent"
				label={__('Apply type', 'jet-engine-divi-views')}
				description=""
			>
				<SelectContainer
					options={convertSimpleOptions([
						{ value: 'ajax', label: __('AJAX', 'jet-engine-divi-views') },
						{ value: 'reload', label: __('Page reload', 'jet-engine-divi-views') },
					])}
				/>
			</FieldContainer>

			<FieldContainer
				attrName="apply_button_text.innerContent"
				label={__('Apply button text', 'jet-engine-divi-views')}
				description=""
			>
				<TextContainer />
			</FieldContainer>

				<FieldContainer
					attrName="apply_redirect.innerContent"
					label={__('Apply redirect', 'jet-engine-divi-views')}
					description=""
				>
					<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'apply_redirect' ) } />
				</FieldContainer>

			{applyRedirect && (
				<FieldContainer
					attrName="redirect_path.innerContent"
					label={__('Redirect path', 'jet-engine-divi-views')}
					description=""
				>
					<TextContainer />
				</FieldContainer>
			)}

			<FieldContainer
				attrName="active_state.innerContent"
				label={__('Active button state', 'jet-engine-divi-views')}
				description=""
			>
				<SelectContainer
					options={convertSimpleOptions([
						{ value: 'always', label: __('Always', 'jet-engine-divi-views') },
						{ value: 'any', label: __('Any filter selected', 'jet-engine-divi-views') },
						{ value: 'all', label: __('All filters selected', 'jet-engine-divi-views') },
					])}
				/>
			</FieldContainer>

			{activeState && activeState !== 'always' && (
				<FieldContainer
					attrName="if_inactive.innerContent"
					label={__('If button inactive', 'jet-engine-divi-views')}
					description=""
				>
					<SelectContainer
						options={convertSimpleOptions([
							{ value: 'disable', label: __('Disable', 'jet-engine-divi-views') },
							{ value: 'hide', label: __('Hide', 'jet-engine-divi-views') },
						])}
					/>
				</FieldContainer>
			)}

			<FieldContainer
				attrName="query_id.innerContent"
				label={__('Query ID', 'jet-engine-divi-views')}
				description={__(
					'Set unique query ID if you use multiple blocks of same provider on the page.',
					'jet-engine-divi-views'
				)}
			>
				<TextContainer />
			</FieldContainer>
		</GroupContainer>

		<AdminLabelGroup
			defaultGroupAttr={defaultSettingsAttrs?.module?.meta?.adminLabel}
		/>
	</React.Fragment>
};
