// 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';

// Local dependencies.
import { PaginationAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getEffectiveAttrValue,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

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

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

const PAGINATION_DEFAULTS_FALLBACK: Record<string, any> = {
	content_provider: 'not-selected',
	apply_type: 'ajax',
	query_id: '',
	enable_items: true,
	pages_center_offset: 0,
	pages_end_offset: 0,
	enable_prev_next: true,
	prev_text: __( 'Prev Text', 'jet-engine-divi-views' ),
	next_text: __( 'Next Text', 'jet-engine-divi-views' ),
	hide_inactive_prev_next: true,
	enable_load_more: false,
	load_more_text: __( 'Load More', 'jet-engine-divi-views' ),
	autoscroll: true,
	provider_top_offset: 0,
	additional_providers_enabled: false,
	additional_providers_list: [
		{
			additional_provider: '',
			additional_providers_list: '',
		},
	],
};

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

const PAGINATION_TOGGLE_ATTRS = new Set( [
	'enable_items',
	'enable_prev_next',
	'hide_inactive_prev_next',
	'enable_load_more',
	'autoscroll',
] );

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: paginationDefaults,
			toggleKeys: PAGINATION_TOGGLE_ATTRS,
			selectKeys: PAGINATION_SELECT_ATTRS,
		} );

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

	const getToggleDefaultAttr = ( key: string ) => buildDefaultInnerContent( {
		key,
		value: paginationDefaults[ key ],
		toggleKeys: PAGINATION_TOGGLE_ATTRS,
		selectKeys: PAGINATION_SELECT_ATTRS,
	} );

	const getValue = ( key: string ) => getEffectiveAttrValue( {
		attrs,
		key,
		defaults: paginationDefaults,
		toggleKeys: PAGINATION_TOGGLE_ATTRS,
		selectKeys: PAGINATION_SELECT_ATTRS,
	} );

	const itemsEnabled = isToggleEnabledValue( getValue( 'enable_items' ) );
	const prevNextEnabled = isToggleEnabledValue( getValue( 'enable_prev_next' ) );
	const loadMoreEnabled = isToggleEnabledValue( getValue( 'enable_load_more' ) );
	const autoscrollEnabled = isToggleEnabledValue( getValue( 'autoscroll' ) );

	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: 'mixed', label: __('AJAX + page reload', '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>
			</GroupContainer>

			<GroupContainer
				id="controls"
				title={__('Controls', 'jet-engine-divi-views')}
			>
				<FieldContainer
					attrName="enable_items.innerContent"
					label={__('Enable Items', 'jet-engine-divi-views')}
					description=""
				>
					<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'enable_items' ) } />
				</FieldContainer>

				{itemsEnabled && (
					<>
						<FieldContainer
							attrName="pages_center_offset.innerContent"
							label={__('Items center offset', 'jet-engine-divi-views')}
							description=""
						>
							<TextContainer type="number" min={0} max={50} />
						</FieldContainer>

						<FieldContainer
							attrName="pages_end_offset.innerContent"
							label={__('Items edge offset', 'jet-engine-divi-views')}
							description=""
						>
							<TextContainer type="number" min={0} max={50} />
						</FieldContainer>
					</>
				)}

				<FieldContainer
					attrName="enable_prev_next.innerContent"
					label={__('Enable Prev/Next buttons', 'jet-engine-divi-views')}
					description=""
				>
					<ToggleContainer defaultAttr={ getToggleDefaultAttr( 'enable_prev_next' ) } />
				</FieldContainer>

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

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

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

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

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

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

				{autoscrollEnabled && (
					<FieldContainer
						attrName="provider_top_offset.innerContent"
						label={__('Provider top offset', 'jet-engine-divi-views')}
						description=""
					>
						<TextContainer type="number" min={0} max={300} />
					</FieldContainer>
				)}
			</GroupContainer>

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