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

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

// Divi dependencies.
import {
	FieldContainer,
	AdminLabelGroup,
} from '@divi/module';
import { GroupContainer } from '@divi/modal';
import {
	TextContainer,
	ToggleContainer,
	SelectContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { RatingFilterAttrs } from './types';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getBlockDefaultsFromSchema,
	getEffectiveAttrValue,
	isToggleEnabled as isToggleEnabledValue,
} from '../../utils';

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

const getAvailableFilters = ( filterType: string ) => {
	const filters = window.JSFDiviViews.filters || {};
	return convertObjectOptions( filters[ filterType ] || [] );
};

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

const RATING_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: '',
	rating_icon: 'star',
	hide_apply_button: false,
	apply_redirect: false,
	apply_indexer: false,
	show_counter: false,
	counter_prefix: '(',
	counter_suffix: ')',
	show_items_rule: 'show',
	change_items_rule: 'always',
};

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

const RATING_FILTER_TOGGLE_ATTRS = new Set( [
	'apply_button',
	'hide_apply_button',
	'apply_redirect',
	'show_label',
	'apply_indexer',
	'show_counter',
] );

const getRatingIconOptions = () => convertSimpleOptions( [
	{ value: 'star', label: __( 'Star', 'jet-engine-divi-views' ) },
	{ value: 'star-o', label: __( 'Star Outline', 'jet-engine-divi-views' ) },
	{ value: 'star-half', label: __( 'Half Star', 'jet-engine-divi-views' ) },
	{ value: 'star-half-o', label: __( 'Half Star Outline', 'jet-engine-divi-views' ) },
] );

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

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

	const defaults = getBlockDefaultsFromSchema( 'rating', RATING_FILTER_DEFAULTS_FALLBACK );

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults,
			toggleKeys: RATING_FILTER_TOGGLE_ATTRS,
			selectKeys: RATING_FILTER_SELECT_ATTRS,
		} );

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

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

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

	const applyOn = getValue( 'apply_on' );
	const applyButton = isToggleEnabledValue( getValue( 'apply_button' ) );

	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( 'rating' ) } />
			</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="rating_icon.innerContent"
				label={ __( 'Rating icon', 'jet-engine-divi-views' ) }
				description=""
			>
				<SelectContainer options={ getRatingIconOptions() } />
			</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>

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