import React from 'react';
import { __ } from '@wordpress/i18n';
import { GroupContainer } from '@divi/modal';
import { FieldContainer } from '@divi/module';
import {
	SelectContainer,
	ToggleContainer,
	TextContainer,
} from '@divi/field-library';
import {
	buildDefaultAttrsPatch,
	buildDefaultInnerContent,
	convertObjectOptions,
	convertSimpleOptions,
	getEffectiveAttrValue,
	isToggleEnabled,
} from '../utils';
import { type Module } from '@divi/types';

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);
};

interface Props<T> extends Module.Settings.Panel.Props<T> {
	filterType: string;
	defaults?: Record<string, any>;
	toggleKeys?: Set<string> | string[];
	selectKeys?: Set<string> | string[];
}

export const FilterGeneralSettingsPanel = <T extends Record<string, any>>(
	props: Props<T>
): React.ReactElement => {
	const { attrs, filterType } = props;
	const setAttrs = ( props as unknown as {
		setAttrs?: ( next: Partial<T> ) => void;
	} ).setAttrs || ( props as unknown as {
		setAttributes?: ( next: Partial<T> ) => void;
	} ).setAttributes || ( props as unknown as {
		onChange?: ( next: Partial<T> ) => void;
	} ).onChange;
	const defaults = props.defaults || {
		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: '',
	};
	const toggleKeys = Array.from( props.toggleKeys || [ 'apply_button', 'show_label' ] );
	const selectKeys = Array.from( props.selectKeys || [ 'content_provider', 'apply_type', 'apply_on' ] );

	React.useEffect( () => {
		const patch = buildDefaultAttrsPatch( {
			attrs,
			defaults,
			toggleKeys,
			selectKeys,
		} );

		if ( Object.keys( patch ).length ) {
			setAttrs?.( patch as Partial<T> );
		}
	}, [ attrs, setAttrs ] );

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

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

	return (
		<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(filterType)} />
			</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>

			<FieldContainer
				attrName="apply_button.innerContent"
				label={__('Show apply button', 'jet-engine-divi-views')}
				description=""
			>
				<ToggleContainer
					defaultAttr={ buildDefaultInnerContent( {
						key: 'apply_button',
						value: defaults.apply_button,
						toggleKeys,
					} ) }
				/>
			</FieldContainer>

			{applyButton && applyOn === 'submit' && (
				<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={ buildDefaultInnerContent( {
						key: 'show_label',
						value: defaults.show_label,
						toggleKeys,
					} ) }
				/>
			</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>
	);
};
