// 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 {
	SelectContainer,
	TextContainer,
	ToggleContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { SelectFilterAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getBlockDefaultsFromSchema,
	getEffectiveAttrValue,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

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

const SELECT_FILTER_DEFAULTS_FALLBACK: Record<string, any> = {
	filter_id: 0,
	content_provider: 'not-selected',
	apply_type: 'ajax',
	apply_on: 'value',
	apply_button: true,
	apply_button_text: __( 'Apply filter', 'jet-engine-divi-views' ),
	show_label: false,
	query_id: '',
	apply_indexer: false,
	show_counter: false,
	counter_prefix: '(',
	counter_suffix: ')',
	show_items_rule: 'show',
	change_items_rule: 'always',
};

const SELECT_FILTER_SELECT_ATTRS = new Set( [
	'content_provider',
	'apply_type',
	'apply_on',
	'show_items_rule',
	'change_items_rule',
] );

const SELECT_FILTER_TOGGLE_ATTRS = new Set( [
	'apply_button',
	'show_label',
	'apply_indexer',
	'show_counter',
] );

const getAvailableFilters = () => {
	const filters = window.JSFDiviViews?.filters || {};

	return convertObjectOptions( filters.select || [] );
};

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

	return convertObjectOptions( providers );
};

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

	const selectFilterDefaults = getBlockDefaultsFromSchema( 'select', SELECT_FILTER_DEFAULTS_FALLBACK );

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: selectFilterDefaults,
			toggleKeys: SELECT_FILTER_TOGGLE_ATTRS,
			selectKeys: SELECT_FILTER_SELECT_ATTRS,
		} );

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

	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: selectFilterDefaults[ key ],
			toggleKeys: SELECT_FILTER_TOGGLE_ATTRS,
			selectKeys: SELECT_FILTER_SELECT_ATTRS,
		} );
	};

	const getValue = ( key: string ) => {
		return getEffectiveAttrValue( {
			attrs,
			key,
			defaults: selectFilterDefaults,
			toggleKeys: SELECT_FILTER_TOGGLE_ATTRS,
			selectKeys: SELECT_FILTER_SELECT_ATTRS,
		} );
	};

	const applyOn = getValue( 'apply_on' );
	const applyButton = isToggleEnabledValue( getValue( 'apply_button' ) );
	const applyIndexer = isToggleEnabledValue( getValue( 'apply_indexer' ) );
	const showCounter = isToggleEnabledValue( getValue( 'show_counter' ) );

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

			<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: 'mixed', label: __( 'AJAX + page reload', 'jet-engine-divi-views' ) },
						{ value: 'reload', label: __( 'Page reload', 'jet-engine-divi-views' ) },
					] ) }
				/>
			</FieldContainer>

			<FieldContainer
				attrName="apply_on.innerContent"
				label={__('Apply on', 'jet-engine-divi-views')}
				description=""
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{ value: 'value', label: __( 'Value change', 'jet-engine-divi-views' ) },
						{ value: 'submit', label: __( 'Click on apply button', 'jet-engine-divi-views' ) },
					] ) }
				/>
			</FieldContainer>

			{ 'submit' === applyOn && (
				<FieldContainer
					attrName="apply_button.innerContent"
					label={__('Show apply button', 'jet-engine-divi-views')}
					description=""
				>
					<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'apply_button' ) } />
				</FieldContainer>
			) }

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

			<FieldContainer
				attrName="show_label.innerContent"
				label={__('Show filter label', 'jet-engine-divi-views')}
				description=""
			>
				<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'show_label' ) } />
			</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>

		<GroupContainer
			id="indexer"
			title={__('Indexer', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="apply_indexer.innerContent"
				label={__('Apply Indexer', 'jet-engine-divi-views')}
				description=""
			>
				<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'apply_indexer' ) } />
			</FieldContainer>

			{ applyIndexer && (
				<div>
					<FieldContainer
						attrName="show_counter.innerContent"
						label={__('Show Counter', 'jet-engine-divi-views')}
						description=""
					>
						<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'show_counter' ) } />
					</FieldContainer>

					{ showCounter && (
						<div>
							<FieldContainer
								attrName="counter_prefix.innerContent"
								label={__('Counter Prefix', 'jet-engine-divi-views')}
								description=""
							>
								<TextContainer />
							</FieldContainer>

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

					<FieldContainer
						attrName="show_items_rule.innerContent"
						label={__('If Item Empty', 'jet-engine-divi-views')}
						description=""
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{ value: 'always', label: __( 'Always show', 'jet-engine-divi-views' ) },
								{ value: 'hide', label: __( 'Hide if empty', 'jet-engine-divi-views' ) },
							] ) }
						/>
					</FieldContainer>

					<FieldContainer
						attrName="change_items_rule.innerContent"
						label={__('Change Counters', 'jet-engine-divi-views')}
						description=""
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{ value: 'replace', label: __( 'Replace counters', 'jet-engine-divi-views' ) },
								{ value: 'add', label: __( 'Add to counters', 'jet-engine-divi-views' ) },
							] ) }
						/>
					</FieldContainer>
				</div>
			) }
		</GroupContainer>

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