// 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,
	ToggleContainer,
	SelectContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { ActiveTagsAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	convertObjectOptions,
	convertSimpleOptions,
	getEffectiveAttrValue,
} from '../../utils';

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

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

const ACTIVE_TAGS_DEFAULTS: Record<string, any> = {
	content_provider: 'not-selected',
	apply_type: 'ajax',
	tags_label: __( 'Active tags:', 'jet-engine-divi-views' ),
	query_id: '',
	clear_item: false,
	clear_item_label: __( 'Clear', 'jet-engine-divi-views' ),
	additional_providers_enabled: false,
	additional_providers_list: [
		{
			additional_provider: '',
			additional_providers_list: '',
		},
	],
};

const ACTIVE_TAGS_SELECT_ATTRS = new Set( [
	'content_provider',
	'apply_type',
] );

const ACTIVE_TAGS_TOGGLE_ATTRS = new Set( [
	'clear_item',
	'additional_providers_enabled',
] );

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: ACTIVE_TAGS_DEFAULTS,
			toggleKeys: ACTIVE_TAGS_TOGGLE_ATTRS,
			selectKeys: ACTIVE_TAGS_SELECT_ATTRS,
		} );

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

	const getValue = ( key: string ) => getEffectiveAttrValue( {
		attrs,
		key,
		defaults: ACTIVE_TAGS_DEFAULTS,
		toggleKeys: ACTIVE_TAGS_TOGGLE_ATTRS,
		selectKeys: ACTIVE_TAGS_SELECT_ATTRS,
	} );

	const clearItemEnabled = !! getValue( 'clear_item' );

	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="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>

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

			<FieldContainer
				attrName="clear_item.innerContent"
				label={ __( 'Clear item', 'jet-engine-divi-views' ) }
				description=""
			>
				<ToggleContainer />
			</FieldContainer>

			{ clearItemEnabled && (
				<FieldContainer
					attrName="clear_item_label.innerContent"
					label={ __( 'Clear item label', 'jet-engine-divi-views' ) }
					description=""
				>
					<TextContainer />
				</FieldContainer>
			) }
		</GroupContainer>

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