// 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
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { ListingGridAttrs } from './types';
import {
	convertSimpleOptions,
	convertGroupedOptions,
	buildDefaultInnerContent,
	buildDefaultAttrsPatch,
	getBlockDefaultsFromSchema,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';
import CustomControl from '../../custom-control';

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

const LISTING_GRID_DEFAULTS_FALLBACK: Record<string, any> = {
	lisitng_id: '',
	list_tags_selection: '',
	columns: 3,
	columns_tablet: 3,
	columns_mobile: 1,
	column_min_width: 240,
	column_min_width_tablet: 240,
	column_min_width_mobile: 240,
	is_archive_template: false,
	post_status: [ 'publish' ],
	use_random_posts_num: false,
	posts_num: 6,
	max_posts_num: 6,
	is_masonry: false,
	use_custom_post_types: false,
	custom_post_types: [],
	equal_columns_height: false,
	custom_query: false,
	custom_query_id: '',
	not_found_message: 'No data was found',
	custom_posts_query: '',
	posts_query: [],
	hide_widget_if: '',
	lazy_load: false,
	lazy_load_offset: 0,
	use_load_more: false,
	load_more_type: 'click',
	load_more_id: '',
	load_more_offset: 0,
	loader_text: '',
	loader_spinner: false,
	carousel_enabled: false,
	slides_to_scroll: 1,
	arrows: true,
	dots: false,
	autoplay: true,
	autoplay_speed: 5000,
	pause_on_hover: true,
	infinite: true,
	center_mode: false,
	effect: 'slide',
	speed: 500,
	scroll_slider_enabled: false,
	scroll_slider_on: [ 'desktop', 'tablet', 'mobile' ],
	static_column_width: 200,
	static_column_width_tablet: 200,
	static_column_width_mobile: 200,
	terms_object_ids: '',
	terms_orderby: 'name',
	terms_order: 'DESC',
	terms_hide_empty: true,
	terms_include: '',
	terms_exclude: '',
	terms_offset: '0',
	terms_parent: '',
	terms_child_of: '',
	terms_meta_query: [],
	term_meta_query_relation: 'AND',
	meta_query_relation: 'AND',
	tax_query_relation: 'AND',
	users_meta_query_relation: 'AND',
	users_role__in: [],
	users_role__not_in: [],
	users_include: '',
	users_exclude: '',
	users_search_query: '',
	users_search_columns: [],
	users_meta_query: [],
	_block_id: '',
	_element_id: '',
};

const LISTING_GRID_SELECT_ATTRS = new Set( [
	'lisitng_id',
	'list_tags_selection',
	'columns',
	'columns_tablet',
	'columns_mobile',
	'custom_query_id',
	'hide_widget_if',
	'load_more_type',
	'effect',
	'terms_orderby',
	'terms_order',
	'term_meta_query_relation',
	'meta_query_relation',
	'tax_query_relation',
	'users_meta_query_relation',
] );

const LISTING_GRID_TOGGLE_ATTRS = new Set( [
	'is_archive_template',
	'use_random_posts_num',
	'is_masonry',
	'use_custom_post_types',
	'equal_columns_height',
	'custom_query',
	'lazy_load',
	'use_load_more',
	'loader_spinner',
	'carousel_enabled',
	'arrows',
	'dots',
	'autoplay',
	'pause_on_hover',
	'infinite',
	'center_mode',
	'scroll_slider_enabled',
	'terms_hide_empty',
] );

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

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: getBlockDefaultsFromSchema( 'listingGrid', LISTING_GRID_DEFAULTS_FALLBACK ),
			toggleKeys: LISTING_GRID_TOGGLE_ATTRS,
			selectKeys: LISTING_GRID_SELECT_ATTRS,
		} );

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

	const listingGridDefaults = getBlockDefaultsFromSchema( 'listingGrid', LISTING_GRID_DEFAULTS_FALLBACK );
	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: listingGridDefaults[ key ],
			toggleKeys: LISTING_GRID_TOGGLE_ATTRS,
			selectKeys: LISTING_GRID_SELECT_ATTRS,
		} );
	};


	const columnsOptions = [
		{
			value: 1,
			label: 1
		},
		{
			value: 2,
			label: 2
		},
		{
			value: 3,
			label: 3
		},
		{
			value: 4,
			label: 4
		},
		{
			value: 5,
			label: 5
		},
		{
			value: 6,
			label: 6
		},
		{
			value: 7,
			label: 7
		},
		{
			value: 8,
			label: 8
		},
		{
			value: 9,
			label: 9
		},
		{
			value: 10,
			label: 10
		},
		{
			value: 'auto',
			label: 'Auto'
		}
	];

	const isMasonry = function() {

		if ( 'auto' === attrs?.columns?.innerContent?.desktop?.value
			|| 'auto' === attrs?.columns_tablet?.innerContent?.desktop?.value
			|| 'auto' === attrs?.columns_mobile?.innerContent?.desktop?.value
		) {
			return false;
		}

		return 'on' === attrs?.is_masonry?.innerContent?.desktop?.value;
	};

	const hasScrollSliderOn = () => {
		const value = attrs?.scroll_slider_on?.innerContent?.desktop?.value;

		if ( Array.isArray( value ) ) {
			return value.length > 0;
		}

		return !! value && value !== 'off';
	};

	const getAttrValue = ( key: string ) => attrs?.[ key ]?.innerContent?.desktop?.value;

	const isToggleEnabled = ( value: unknown ): boolean => {
		return isToggleEnabledValue( value );
	};

	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="lisitng_id.innerContent"
				label={__('Listing', 'jet-engine-divi-views')}
				description={__('Select a base listing item', 'jet-engine-divi-views')}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.listingOptions ) }
				/>
			</FieldContainer>

			<FieldContainer
				attrName="list_tags_selection.innerContent"
				label={__('Wrapper Tags', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: '',
							label: __( 'Default (DIV > DIV)' ),
						},
						{
							value: 'ul_li',
							label: __( 'Unordered list (UL > LI)' ),
						},
						{
							value: 'ol_li',
							label: __( 'Ordered list (OL > LI)' ),
						},
					] ) }
				/>
			</FieldContainer>
			<FieldContainer
				attrName="columns.innerContent"
				label={__('Columns Number', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( columnsOptions ) }
				/>
			</FieldContainer>

			{ 'auto' === attrs?.columns?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="column_min_width.innerContent"
					label={__('Column Min Width', 'jet-engine-divi-views')}
					description={ '' }
				>
					<TextContainer type="number" min={0} max={1200} />
				</FieldContainer>
			}

			<FieldContainer
				attrName="columns_tablet.innerContent"
				label={__('Columns Number(Tablet)', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( columnsOptions ) }
				/>
			</FieldContainer>

			{ 'auto' === attrs?.columns_tablet?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="column_min_width_tablet.innerContent"
					label={__('Column Min Width (Tablet)', 'jet-engine-divi-views')}
					description={ '' }
				>
					<TextContainer type="number" min={0} max={800} />
				</FieldContainer>
			}

			<FieldContainer
				attrName="columns_mobile.innerContent"
				label={__('Columns Number(Mobile)', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( columnsOptions ) }
				/>
			</FieldContainer>

			{ 'auto' === attrs?.columns_mobile?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="column_min_width_mobile.innerContent"
					label={__('Column Min Width (Mobile)', 'jet-engine-divi-views')}
					description={ '' }
				>
					<TextContainer type="number" min={0} max={480} />
				</FieldContainer>
			}

			<FieldContainer
				attrName="is_archive_template.innerContent"
				label={ __('Use as Archive Template', 'jet-engine-divi-views') }
				description={''}
				defaultAttr={ getToggleDefaultAttr( 'is_archive_template' ) }
			>
				<ToggleContainer />
			</FieldContainer>

			<FieldContainer
				attrName="post_status.innerContent"
				label={__('Status', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: 'publish',
							label: __( 'Publish' ),
						},
						{
							value: 'future',
							label: __( 'Future' ),
						},
						{
							value: 'draft',
							label: __( 'Draft' ),
						},
						{
							value: 'pending',
							label: __( 'Pending Review' ),
						},
						{
							value: 'private',
							label: __( 'Private' ),
						},
					] ) }
				/>
			</FieldContainer>

			<FieldContainer
				attrName="use_random_posts_num.innerContent"
				label={ __('Use Random posts number', 'jet-engine-divi-views') }
				description={''}
				defaultAttr={ getToggleDefaultAttr( 'use_random_posts_num' ) }
			>
				<ToggleContainer />
			</FieldContainer>

			<FieldContainer
				attrName="posts_num.innerContent"
				label={ isToggleEnabled( attrs?.use_random_posts_num?.innerContent?.desktop?.value ) ? __( 'Min posts number' ) : __( 'Posts number' ) }
				description={ '' }
			>
				<TextContainer type="number" min={1} max={1000} />
			</FieldContainer>

			{ isToggleEnabled( attrs?.use_random_posts_num?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="max_posts_num.innerContent"
					label={ __( 'Max Posts number' ) }
					description={ '' }
				>
					<TextContainer type="number" min={1} max={1000} />
				</FieldContainer>
			}

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

			<FieldContainer
				attrName="lazy_load.innerContent"
				label={ __('Lazy load', 'jet-engine-divi-views') }
				description={ __( 'Lazy load the listing for boosts rendering performance.' ) }
				defaultAttr={ getToggleDefaultAttr( 'lazy_load' ) }
			>
				<ToggleContainer />
			</FieldContainer>

			{ isToggleEnabled( attrs?.lazy_load?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="lazy_load_offset.innerContent"
					label={ __( 'Lazy load offset' ) }
					description={ '' }
				>
					<TextContainer type="number" min={0} max={500} />
				</FieldContainer>
			}

			{ 'auto' !== attrs?.columns?.innerContent?.desktop?.value &&
				'auto' !== attrs?.columns_mobile?.innerContent?.desktop?.value &&
				'auto' !== attrs?.columns_tablet?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="is_masonry.innerContent"
					label={ __( 'Is masonry grid' ) }
					description={ '' }
					defaultAttr={ getToggleDefaultAttr( 'is_masonry' ) }
				>
					<ToggleContainer />
				</FieldContainer>
			}

			{ ! isMasonry() &&
				<FieldContainer
					attrName="equal_columns_height.innerContent"
					label={ __( 'Equal columns height' ) }
					description={ __( 'Fits only top level sections of grid item' ) }
					defaultAttr={ getToggleDefaultAttr( 'equal_columns_height' ) }
				>
					<ToggleContainer />
				</FieldContainer>
			}

			<FieldContainer
				attrName="use_load_more.innerContent"
				label={ __( 'Load more' ) }
				description={ '' }
				defaultAttr={ getToggleDefaultAttr( 'use_load_more' ) }
			>
				<ToggleContainer />
			</FieldContainer>

			{ isToggleEnabled( attrs?.use_load_more?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="load_more_type.innerContent"
					label={__('Load more type', 'jet-engine-divi-views')}
					description={''}
				>
					<SelectContainer
						options={convertSimpleOptions([
							{
								value: 'click',
								label: __('By Click'),
							},
							{
								value: 'scroll',
								label: __('Infinite Scroll'),
							},
						])}
					/>
				</FieldContainer>
			}

			{ isToggleEnabled( attrs?.use_load_more?.innerContent?.desktop?.value ) &&
				'click' === attrs?.load_more_type?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="load_more_id.innerContent"
					label={ __('Load more element ID', 'jet-engine-divi-views') }
					description={ __( 'Please, make sure to add a Button block that will be used as "Load more" button' ) }
				>
					<TextContainer/>
				</FieldContainer>
			}

			{ isToggleEnabled( attrs?.use_load_more?.innerContent?.desktop?.value ) &&
				'scroll' === attrs?.load_more_type?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="load_more_offset.innerContent"
					label={ __('Load more offset', 'jet-engine-divi-views') }
					description={ '' }
				>
					<TextContainer/>
				</FieldContainer>
			}

			{ isToggleEnabled( attrs?.use_load_more?.innerContent?.desktop?.value ) &&
				<>
					<FieldContainer
						attrName="loader_text.innerContent"
						label={ __('Loader text', 'jet-engine-divi-views') }
						description={ '' }
					>
						<TextContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="loader_spinner.innerContent"
						label={ __( 'Show loader spinner' ) }
						description={ '' }
						defaultAttr={ getToggleDefaultAttr( 'loader_spinner' ) }
					>
						<ToggleContainer />
					</FieldContainer>
				</>

			}
		</GroupContainer>

		{ ! window.JetEngineDiviViews?.legacy?.is_disabled &&
			<GroupContainer
				id="legacy-post-types"
				title={__('Post Types', 'jet-engine-divi-views')}
			>
				<FieldContainer
					attrName="use_custom_post_types.innerContent"
					label={ __('Use Custom Post Types', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'use_custom_post_types' ) }
				>
					<ToggleContainer />
				</FieldContainer>

				{ isToggleEnabled( attrs?.use_custom_post_types?.innerContent?.desktop?.value ) &&
					<FieldContainer
						attrName="custom_post_types.innerContent"
						label={__('Post types', 'jet-engine-divi-views')}
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( window.JetEngineDiviViews.postTypes ) }
						/>
					</FieldContainer>
				}
			</GroupContainer>
		}

		<GroupContainer
			id="custom-query"
			title={__('Custom Query', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="custom_query.innerContent"
				label={ __('Use Custom Query', 'jet-engine-divi-views') }
				description={''}
				defaultAttr={ getToggleDefaultAttr( 'custom_query' ) }
			>
				<ToggleContainer />
			</FieldContainer>

			{ isToggleEnabled( attrs?.custom_query?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="custom_query_id.innerContent"
					label={__('Custom Query', 'jet-engine-divi-views')}
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( window.JetEngineDiviViews.queriesList ) }
					/>
				</FieldContainer>
			}
		</GroupContainer>

		<GroupContainer
			id="block-visibility"
			title={__('Block Visibility', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="hide_widget_if.innerContent"
				label={__('Hide block if', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.hideOptions || [] ) }
				/>
			</FieldContainer>
		</GroupContainer>

		<GroupContainer
			id="slider-settings"
			title={__('Slider Settings', 'jet-engine-divi-views')}
		>
			{ !isMasonry() && ! isToggleEnabled( getAttrValue( 'scroll_slider_enabled' ) ) &&
				<FieldContainer
					attrName="carousel_enabled.innerContent"
					label={__('Enable Slider', 'jet-engine-divi-views')}
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'carousel_enabled' ) }
				>
					<ToggleContainer/>
				</FieldContainer>
			}

			{ !isMasonry() && isToggleEnabled( getAttrValue( 'carousel_enabled' ) ) &&
				<>
					{ [ 'ul_li', 'ol_li' ].includes( attrs?.list_tags_selection?.innerContent?.desktop?.value ) &&
						<div className="et-vb-field">
							<div className="et-fb-description">
								{ __( 'Note: Slider wrappers make UL/OL markup invalid by W3C standards.', 'jet-engine-divi-views' ) }
							</div>
						</div>
					}
					<FieldContainer
						attrName="slides_to_scroll.innerContent"
						label={ __( 'Slides to Scroll' ) }
						description={ '' }
					>
						<TextContainer type="number" min={1} max={4} />
					</FieldContainer>
					<FieldContainer
						attrName="arrows.innerContent"
						label={__('Show Arrows Navigation', 'jet-engine-divi-views')}
						description={''}
						defaultAttr={ getToggleDefaultAttr( 'arrows' ) }
					>
						<ToggleContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="dots.innerContent"
						label={__('Show Dots Navigation', 'jet-engine-divi-views')}
						description={''}
						defaultAttr={ getToggleDefaultAttr( 'dots' ) }
					>
						<ToggleContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="autoplay.innerContent"
						label={__('Autoplay', 'jet-engine-divi-views')}
						description={''}
						defaultAttr={ getToggleDefaultAttr( 'autoplay' ) }
					>
						<ToggleContainer/>
					</FieldContainer>

					{ isToggleEnabled( attrs?.autoplay?.innerContent?.desktop?.value ) &&
						<>
							<FieldContainer
								attrName="autoplay_speed.innerContent"
								label={ __( 'Autoplay Speed' ) }
								description={ '' }
							>
								<TextContainer type="number" min={1000} max={10000} />
							</FieldContainer>
							<FieldContainer
								attrName="pause_on_hover.innerContent"
								label={__('Pause On Hover', 'jet-engine-divi-views')}
								description={''}
								defaultAttr={ getToggleDefaultAttr( 'pause_on_hover' ) }
							>
								<ToggleContainer/>
							</FieldContainer>
						</>
					}

					<FieldContainer
						attrName="effect.innerContent"
						label={__('Effect', 'jet-engine-divi-views')}
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'slide',
									label: __( 'Slide' ),
								},
								{
									value: 'fade',
									label: __( 'Fade' ),
								},
							] )}
						/>
					</FieldContainer>

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

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

					<FieldContainer
						attrName="speed.innerContent"
						label={ __( 'Animation Speed' ) }
						description={ '' }
					>
						<TextContainer type="number" min={1000} max={10000} />
					</FieldContainer>

				</>
			}

			{ !isMasonry() && ! isToggleEnabled( getAttrValue( 'carousel_enabled' ) ) &&
				<FieldContainer
					attrName="scroll_slider_enabled.innerContent"
					label={__('Enable Scroll Slider', 'jet-engine-divi-views')}
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'scroll_slider_enabled' ) }
				>
					<ToggleContainer/>
				</FieldContainer>
			}

			{ !isMasonry() && isToggleEnabled( getAttrValue( 'scroll_slider_enabled' ) ) &&
				<>
					<FieldContainer
						attrName="scroll_slider_on.innerContent"
						label={__('Scroll Slider On', 'jet-engine-divi-views')}
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'desktop',
									label: __( 'Desktop' ),
								},
								{
									value: 'tablet',
									label: __( 'Tablet' ),
								},
								{
									value: 'mobile',
									label: __( 'Mobile' ),
								},
							] )}
						/>
					</FieldContainer>

					{ hasScrollSliderOn() &&
						<FieldContainer
							attrName="static_column_width.innerContent"
							label={ __( 'Static column width' ) }
							description={ '' }
						>
							<TextContainer type="number" min={0} max={600} />
						</FieldContainer>
					}
				</>
			}

		</GroupContainer>

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