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

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

// Divi dependencies.
import {
	AdminLabelGroup,
	BackgroundGroup,
	FieldContainer,
	LinkGroup,
} from '@divi/module';
import { GroupContainer } from '@divi/modal';
import {
	TextContainer,
	TextAreaContainer,
	ToggleContainer,
	SelectContainer,
	IconPickerContainer,
	RangeContainer,
	UploadContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { DynamicRepeaterAttrs } from './types';
import {
	convertSimpleOptions,
	convertGroupedOptions,
	buildDefaultInnerContent,
	buildDefaultAttrsPatch,
	getBlockDefaultsFromSchema,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

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

const DYNAMIC_REPEATER_DEFAULTS_FALLBACK: Record<string, any> = {
	dynamic_field_source: '',
	dynamic_field_option: '',
	dynamic_field_format: '<span>%name%</span>',
	item_tag: 'div',
	items_delimiter: '',
	dynamic_field_before: '',
	dynamic_field_after: '',
	dynamic_field_counter: false,
	dynamic_field_leading_zero: false,
	dynamic_field_counter_after: '',
	dynamic_field_counter_position: 'at-left',
	hide_if_empty: false,
	object_context: 'default_object',
	je_query_id: '',
	dynamic_field_fallback: '',
};

const DYNAMIC_REPEATER_SELECT_ATTRS = new Set( [
	'dynamic_field_source',
	'dynamic_field_option',
	'je_query_id',
	'acf_field_key',
	'item_tag',
	'dynamic_field_counter_position',
	'object_context',
] );

const DYNAMIC_REPEATER_TOGGLE_ATTRS = new Set( [
	'dynamic_field_counter',
	'dynamic_field_leading_zero',
	'hide_if_empty',
] );

export const SettingsContent = ( props: Module.Settings.Panel.Props<DynamicRepeaterAttrs> ): ReactElement => {

	const {
		defaultSettingsAttrs,
		attrs
	} = props;
	const setAttrs = ( ( props as unknown as {
		setAttrs?: ( next: Partial<DynamicRepeaterAttrs> ) => void;
		setAttributes?: ( next: Partial<DynamicRepeaterAttrs> ) => void;
	} ).setAttrs || ( props as unknown as {
		onChange?: ( next: Partial<DynamicRepeaterAttrs> ) => void;
		setAttributes?: ( next: Partial<DynamicRepeaterAttrs> ) => void;
	} ).setAttributes || ( props as unknown as {
		onChange?: ( next: Partial<DynamicRepeaterAttrs> ) => void;
	} ).onChange );

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: getBlockDefaultsFromSchema( 'dynamicRepeater', DYNAMIC_REPEATER_DEFAULTS_FALLBACK ),
			toggleKeys: DYNAMIC_REPEATER_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_REPEATER_SELECT_ATTRS,
		} );

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

	const dynamicRepeaterDefaults = getBlockDefaultsFromSchema( 'dynamicRepeater', DYNAMIC_REPEATER_DEFAULTS_FALLBACK );
	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: dynamicRepeaterDefaults[ key ],
			toggleKeys: DYNAMIC_REPEATER_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_REPEATER_SELECT_ATTRS,
		} );
	};

	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="dynamic_field_source.innerContent"
				label={ __('Source', 'jet-engine-divi-views') }
				description={''}
			>
				<SelectContainer
					options={ convertGroupedOptions( window.JetEngineDiviViews.repeaterFields ) }
				/>
			</FieldContainer>

			{ 'options_page' === attrs?.dynamic_field_source?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="dynamic_field_option.innerContent"
					label={ __('Option', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.repeaterOptionsFields ) }
					/>
				</FieldContainer>
			}

			{ 'je_query' === attrs?.dynamic_field_source?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="je_query_id.innerContent"
					label={ __('Query ID', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( window.JetEngineDiviViews.queriesList ) }
					/>
				</FieldContainer>
			}

			{ 'acf_field_groups' === attrs?.dynamic_field_source?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="acf_field_key.innerContent"
					label={ __('ACF Field', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.acfRepeaterFields ) }
					/>
				</FieldContainer>
			}

		</GroupContainer>

		<GroupContainer
			id="layout"
			title={__('Layout', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="dynamic_field_format.innerContent"
				label={ __('Item format', 'jet-engine-divi-views') }
				description={ '' }
			>
				<TextAreaContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="item_tag.innerContent"
				label={ __('Item HTML tag', 'jet-engine-divi-views') }
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: 'div',
							label: 'DIV',
						},
						{
							value: 'tr',
							label: 'TR',
						},
						{
							value: 'li',
							label: 'LI',
						},
					] ) }
				/>
			</FieldContainer>

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

			<FieldContainer
				attrName="dynamic_field_before.innerContent"
				label={ __('Before items markup', 'jet-engine-divi-views') }
				description={ '' }
			>
				<TextAreaContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="dynamic_field_after.innerContent"
				label={ __('After items markup', 'jet-engine-divi-views') }
				description={ '' }
			>
				<TextAreaContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="dynamic_field_counter.innerContent"
				label={ __('Add counter to repeater items', 'jet-engine-divi-views') }
				description={ '' }
				defaultAttr={ getToggleDefaultAttr( 'dynamic_field_counter' ) }
			>
				<ToggleContainer/>
			</FieldContainer>

			{ isToggleEnabledValue( attrs?.dynamic_field_counter?.innerContent?.desktop?.value ) &&
				<div className="et-vb-field">
					<FieldContainer
						attrName="dynamic_field_leading_zero.innerContent"
						label={ __('Add leding zero before counter items', 'jet-engine-divi-views') }
						description={ '' }
						defaultAttr={ getToggleDefaultAttr( 'dynamic_field_leading_zero' ) }
					>
						<ToggleContainer/>
					</FieldContainer>

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

					<FieldContainer
						attrName="dynamic_field_counter_position.innerContent"
						label={ __('Position', 'jet-engine-divi-views') }
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'above',
									label: __( "Above items" ),
								},
								{
									value: 'at-left',
									label: __( "At the left of the items" ),
								},
								{
									value: 'at-right',
									label: __( "At the right of the items" ),
								},
							] ) }
						/>
					</FieldContainer>
				</div>
			}

			<FieldContainer
				attrName="hide_if_empty.innerContent"
				label={ __('Hide if value is empty', 'jet-engine-divi-views') }
				description={ '' }
				defaultAttr={ getToggleDefaultAttr( 'hide_if_empty' ) }
			>
				<ToggleContainer/>
			</FieldContainer>

			{ ! isToggleEnabledValue( attrs?.hide_if_empty?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="dynamic_field_fallback.innerContent"
					label={ __('Fallback', 'jet-engine-divi-views') }
					description={ '' }
				>
					<TextContainer/>
				</FieldContainer>
			}

			<FieldContainer
				attrName="object_context.innerContent"
				label={ __('Context', 'jet-engine-divi-views') }
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.allowedContextList ) }
				/>
			</FieldContainer>

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