// 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 { CheckRangeFilterAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getBlockDefaultsFromSchema,
	getEffectiveAttrValue,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

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

const CHECK_RANGE_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',
	show_items_label: true,
	filter_image_size: 'full',
	clear_item: true,
	search_enabled: false,
	moreless_enabled: false,
	dropdown_enabled: false,
	dropdown_apply_button: false,
	scroll_enabled: false,
	enable_items: true,
	enable_prev_next: true,
	hide_inactive_prev_next: true,
	enable_load_more: false,
	autoscroll: true,
};

const CHECK_RANGE_FILTER_SELECT_ATTRS = new Set( [
	'content_provider',
	'apply_type',
	'apply_on',
	'active_state',
	'if_inactive',
	'argument_type',
	'show_items_rule',
	'change_items_rule',
	'filter_image_size',
] );

const CHECK_RANGE_FILTER_TOGGLE_ATTRS = new Set( [
	'apply_button',
	'hide_apply_button',
	'apply_redirect',
	'show_label',
	'clear_item',
	'additional_providers_enabled',
	'apply_indexer',
	'show_counter',
	'show_items_label',
	'enable_items',
	'enable_prev_next',
	'hide_inactive_prev_next',
	'enable_load_more',
	'autoscroll',
	'search_enabled',
	'moreless_enabled',
	'dropdown_enabled',
	'dropdown_n_selected_enabled',
	'dropdown_apply_button',
	'scroll_enabled',
] );

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

	return convertObjectOptions( filters['check-range'] || [] );
};

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

	return convertObjectOptions( providers );
};

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

	const defaults = getBlockDefaultsFromSchema( 'check-range', CHECK_RANGE_FILTER_DEFAULTS_FALLBACK );

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults,
			toggleKeys: CHECK_RANGE_FILTER_TOGGLE_ATTRS,
			selectKeys: CHECK_RANGE_FILTER_SELECT_ATTRS,
		} );

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

	const getToggleDefaultAttr = ( key: string ) => buildDefaultInnerContent( {
		key,
		value: defaults[ key ],
		toggleKeys: CHECK_RANGE_FILTER_TOGGLE_ATTRS,
		selectKeys: CHECK_RANGE_FILTER_SELECT_ATTRS,
	} );

	const getValue = ( key: string ) => getEffectiveAttrValue( {
		attrs,
		key,
		defaults,
		toggleKeys: CHECK_RANGE_FILTER_TOGGLE_ATTRS,
		selectKeys: CHECK_RANGE_FILTER_SELECT_ATTRS,
	} );

	const applyOn = getValue( 'apply_on' );
	const applyButton = isToggleEnabledValue( getValue( 'apply_button' ) );
	const searchEnabled = isToggleEnabledValue( getValue( 'search_enabled' ) );
	const morelessEnabled = isToggleEnabledValue( getValue( 'moreless_enabled' ) );
	const dropdownEnabled = isToggleEnabledValue( getValue( 'dropdown_enabled' ) );
	const dropdownNSelectedEnabled = isToggleEnabledValue( getValue( 'dropdown_n_selected_enabled' ) );
	const dropdownApplyButton = isToggleEnabledValue( getValue( 'dropdown_apply_button' ) );
	const scrollEnabled = isToggleEnabledValue( getValue( 'scroll_enabled' ) );
	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="additional"
			title={__('Additional Settings', 'jet-engine-divi-views')}
		>
			<FieldContainer attrName="search_enabled.innerContent" label={__('Search Enabled', 'jet-engine-divi-views')} description="">
				<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'search_enabled' ) } />
			</FieldContainer>

			{ searchEnabled && (
				<FieldContainer attrName="search_placeholder.innerContent" label={__('Search Placeholder', 'jet-engine-divi-views')} description="">
					<TextContainer />
				</FieldContainer>
			) }

			<FieldContainer attrName="moreless_enabled.innerContent" label={__('More/Less Enabled', 'jet-engine-divi-views')} description="">
				<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'moreless_enabled' ) } />
			</FieldContainer>

			{ morelessEnabled && (
				<>
					<FieldContainer attrName="less_items_count.innerContent" label={__('Less Items Count', 'jet-engine-divi-views')} description="">
						<TextContainer type="number" min={1} max={50} />
					</FieldContainer>

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

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

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

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

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

					{ dropdownNSelectedEnabled && (
						<>
							<FieldContainer attrName="dropdown_n_selected_number.innerContent" label={__('Number of Named Items', 'jet-engine-divi-views')} description="">
								<TextContainer type="number" min={1} max={50} />
							</FieldContainer>

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

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

					{ dropdownApplyButton && (
						<FieldContainer attrName="dropdown_apply_button_text.innerContent" label={__('Apply Button Text', 'jet-engine-divi-views')} description="">
							<TextContainer />
						</FieldContainer>
					) }
				</>
			) }

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

			{ scrollEnabled && (
				<FieldContainer attrName="scroll_height.innerContent" label={__('Scroll Height (px)', 'jet-engine-divi-views')} description="">
					<TextContainer type="number" min={50} max={1000} />
				</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 && (
				<>
					<FieldContainer attrName="show_counter.innerContent" label={__('Show Counter', 'jet-engine-divi-views')} description="">
						<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'show_counter' ) } />
					</FieldContainer>

					{ showCounter && (
						<>
							<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>
						</>
					) }

					<FieldContainer attrName="show_items_rule.innerContent" label={__('Show Items Rule', 'jet-engine-divi-views')} description="">
						<SelectContainer
							options={ convertSimpleOptions( [
								{ value: 'show', label: __( 'Show matched items', 'jet-engine-divi-views' ) },
								{ value: 'hide', label: __( 'Hide unmatched items', 'jet-engine-divi-views' ) },
								{ value: 'disable', label: __( 'Disable unmatched items', 'jet-engine-divi-views' ) },
							] ) }
						/>
					</FieldContainer>

					<FieldContainer attrName="change_items_rule.innerContent" label={__('Change Items Rule', 'jet-engine-divi-views')} description="">
						<SelectContainer
							options={ convertSimpleOptions( [
								{ value: 'always', label: __( 'Always', 'jet-engine-divi-views' ) },
								{ value: 'other', label: __( 'Only for other filters', 'jet-engine-divi-views' ) },
							] ) }
						/>
					</FieldContainer>
				</>
			) }
		</GroupContainer>

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