// 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 { DynamicImageAttrs } 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 DYNAMIC_IMAGE_DEFAULTS_FALLBACK: Record<string, any> = {
	dynamic_image_source: 'post_thumbnail',
	dynamic_image_source_custom: '',
	dynamic_field_option: '',
	dynamic_image_size: 'full',
	dynamic_avatar_size: 50,
	custom_aspect_ratio: '',
	custom_image_width: '',
	custom_image_height: '',
	custom_scale: 'cover',
	custom_image_alt: '',
	lazy_load_image: true,
	linked_image: true,
	image_link_source: '_permalink',
	image_link_source_custom: '',
	image_link_option: '',
	open_in_new: false,
	rel_attr: '',
	hide_if_empty: false,
	fallback_image_url: '',
	image_url_prefix: '',
	link_url_prefix: '',
	object_context: 'default_object',
	add_image_caption: false,
	image_caption_position: 'after',
	image_caption: '',
};

const DYNAMIC_IMAGE_SELECT_ATTRS = new Set( [
	'dynamic_image_source',
	'dynamic_field_option',
	'acf_field_key',
	'dynamic_image_size',
	'custom_aspect_ratio',
	'custom_scale',
	'image_link_source',
	'image_link_option',
	'acf_link_field_key',
	'dynamic_link_profile_page',
	'rel_attr',
	'object_context',
	'image_caption_position',
] );

const DYNAMIC_IMAGE_TOGGLE_ATTRS = new Set( [
	'lazy_load_image',
	'linked_image',
	'open_in_new',
	'hide_if_empty',
	'add_image_caption',
] );

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

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: getBlockDefaultsFromSchema( 'dynamicImage', DYNAMIC_IMAGE_DEFAULTS_FALLBACK ),
			toggleKeys: DYNAMIC_IMAGE_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_IMAGE_SELECT_ATTRS,
		} );

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

	const dynamicImageDefaults = getBlockDefaultsFromSchema( 'dynamicImage', DYNAMIC_IMAGE_DEFAULTS_FALLBACK );
	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: dynamicImageDefaults[ key ],
			toggleKeys: DYNAMIC_IMAGE_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_IMAGE_SELECT_ATTRS,
		} );
	};

	const linkFields = JSON.parse( JSON.stringify( window.JetEngineDiviViews.linkFields || [] ) );

	if ( linkFields?.[0]?.values && Array.isArray( linkFields[0].values ) ) {
		const hasFileOption = linkFields[0].values.some( ( item: any ) => item?.value === '_file' );

		if ( ! hasFileOption ) {
			linkFields[0].values.push( {
				label: __( 'Media File', 'jet-engine-divi-views' ),
				value: '_file',
			} );
		}
	}
	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="dynamic_image_source.innerContent"
				label={__('Source', 'jet-engine-divi-views')}
				description={__('Dynamic Field Source.', 'jet-engine-divi-views')}
			>
				<SelectContainer
					options={ convertGroupedOptions( window.JetEngineDiviViews.mediaFields ) }
				/>
			</FieldContainer>

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

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

			<FieldContainer
				attrName="dynamic_image_source_custom.innerContent"
				label={ __('Or set manually', 'jet-engine-divi-views') }
				description={ __('Here you can set the custom/meta field name, repeater key, component control name, etc. Please note that in the case of the custom/meta field name, this option overrides the value selected above.', 'jet-engine-divi-views') }
			>
				<TextContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="image_url_prefix.innerContent"
				label={ __('Image URL Prefix', 'jet-engine-divi-views') }
				description={ __('Add prefix to the image URL. For example for the cases when source contains only part of the URL.', 'jet-engine-divi-views') }
			>
				<TextContainer/>
			</FieldContainer>

		</GroupContainer>

		<GroupContainer
			id="layout"
			title={__('Layout', 'jet-engine-divi-views')}
		>
			{ 'user_avatar' !== attrs?.dynamic_image_source?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="dynamic_image_size.innerContent"
					label={ __('Image Size', 'jet-engine-divi-views') }
					description={__('Description', 'jet-engine-divi-views')}
				>
					<SelectContainer
						options={ convertSimpleOptions( window.JetEngineDiviViews.imageSizes ) }
					/>
				</FieldContainer>
			}

			{ 'user_avatar' === attrs?.dynamic_image_source?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="dynamic_avatar_size.innerContent"
					label={__('Image Size', 'jet-engine-divi-views')}
					description={__('Description', 'jet-engine-divi-views')}
				>
					<RangeContainer
						min={ 10 }
						max={ 500 }
						unit={[]}
					/>
				</FieldContainer>
			}

			<FieldContainer
				attrName="custom_aspect_ratio.innerContent"
				label={__('Aspect Ratio', 'jet-engine-divi-views')}
				description={__('Description', 'jet-engine-divi-views')}
			>
				<SelectContainer
					emptyLabel={__( 'Original' )}
					options={ convertSimpleOptions( [
						{
							value: '',
							label: __( 'Original' ),
						},
						{
							value: '1:1',
							label: __( '1:1' ),
						},
						{
							value: '3:2',
							label: '3:2',
						},
						{
							value: '16:9',
							label: '16:9',
						},
						{
							value: '4:3',
							label: '4:3',
						},
						{
							value: '2:3',
							label: '2:3',
						},
						{
							value: '9:16',
							label: '9:16',
						},
						{
							value: '3:4',
							label: '3:4',
						},
					] ) }
				/>
			</FieldContainer>

			<FieldContainer
				attrName="custom_image_width.innerContent"
				label={__('Image Width', 'jet-engine-divi-views')}
				description={__('Description', 'jet-engine-divi-views')}
			>
				<RangeContainer
					min={ 50 }
					max={ 1000 }
					units={['px', '%']}
				/>
			</FieldContainer>

			<FieldContainer
				attrName="custom_image_height.innerContent"
				label={__('Image Height', 'jet-engine-divi-views')}
				description={__('Description', 'jet-engine-divi-views')}
			>
				<RangeContainer
					min={ 50 }
					max={ 1000 }
					units={['px', '%']}
				/>
			</FieldContainer>

			{ '' !== attrs?.custom_aspect_ratio?.innerContent?.desktop?.value &&
				<FieldContainer
					attrName="custom_scale.innerContent"
					label={ __('Scale', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( [
							{
								value: 'cover',
								label: __( 'Сover' ),
							},
							{
								value: 'contain',
								label: __( 'Сontain' ),
							},
						] ) }
					/>
				</FieldContainer>
			}

			<FieldContainer
				attrName="custom_image_alt.innerContent"
				label={ __('Custom Image Alt', 'jet-engine-divi-views') }
				description={ '' }
			>
				<TextContainer/>
			</FieldContainer>

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

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

			{ isToggleEnabledValue( attrs?.linked_image?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="image_link_source.innerContent"
					label={ __('Source', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertGroupedOptions( linkFields ) }
					/>
				</FieldContainer>
			}

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

			{ isToggleEnabledValue( attrs?.linked_image?.innerContent?.desktop?.value ) &&
				'acf_field_groups' === attrs?.image_link_source?.innerContent?.desktop?.value &&
				undefined !== window.JetEngineDiviViews.acfLinksFields &&
				<FieldContainer
					attrName="acf_link_field_key.innerContent"
					label={ __('ACF Field', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.acfLinksFields ) }
					/>
				</FieldContainer>
			}

			{ isToggleEnabledValue( attrs?.linked_image?.innerContent?.desktop?.value ) &&
				'profile_page' === attrs?.image_link_source?.innerContent?.desktop?.value &&
				undefined !== window.JetEngineDiviViews.profileBuilderPages &&
				<FieldContainer
					attrName="dynamic_link_profile_page.innerContent"
					label={ __('Profile Page', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.profileBuilderPages ) }
					/>
				</FieldContainer>
			}

			{ isToggleEnabledValue( attrs?.linked_image?.innerContent?.desktop?.value ) &&
				<div>
					<FieldContainer
						attrName="image_link_source_custom.innerContent"
						label={ __('Or set manually', 'jet-engine-divi-views') }
						description={ __('Here you can set the custom/meta field name, repeater key, component control name, etc. Please note that in the case of the custom/meta field name, this option overrides the value selected above.', 'jet-engine-divi-views') }
					>
						<TextContainer/>
					</FieldContainer>

					<FieldContainer
						attrName="link_url_prefix.innerContent"
						label={ __('Link URL Prefix', 'jet-engine-divi-views') }
						description={ __('Add prefix to the URL, for example tel:, mailto: etc.', 'jet-engine-divi-views') }
					>
						<TextContainer/>
					</FieldContainer>
				</div>
			}

			<FieldContainer
				attrName="open_in_new.innerContent"
				label={ __('Open in new window', 'jet-engine-divi-views') }
				description={ '' }
				defaultAttr={ getToggleDefaultAttr( 'open_in_new' ) }
			>
				<ToggleContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="rel_attr.innerContent"
				label={ __('Add "rel" attr', 'jet-engine-divi-views') }
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: '',
							label: __( 'No' ),
						},
						{
							value: 'alternate',
							label: __( 'Alternate' ),
						},
						{
							value: 'author',
							label: __( 'Author' ),
						},
						{
							value: 'bookmark',
							label: __( 'Bookmark' ),
						},
						{
							value: 'external',
							label: __( 'External' ),
						},
						{
							value: 'help',
							label: __( 'Help' ),
						},
						{
							value: 'license',
							label: __( 'License' ),
						},
						{
							value: 'next',
							label: __( 'Next' ),
						},
						{
							value: 'nofollow',
							label: __( 'Nofollow' ),
						},
						{
							value: 'noreferrer',
							label: __( 'Noreferrer' ),
						},
						{
							value: 'noopener',
							label: __( 'Noopener' ),
						},
						{
							value: 'prev',
							label: __( 'Prev' ),
						},
						{
							value: 'search',
							label: __( 'Search' ),
						},
						{
							value: 'tag',
							label: __( 'Tag' ),
						},
					] ) }
				/>
			</FieldContainer>

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

			<FieldContainer
				attrName="fallback_image_url.innerContent"
				label={ __('Fallback Image', 'jet-engine-divi-views') }
				description={ '' }
			>
				<UploadContainer/>
			</FieldContainer>

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

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

			{ isToggleEnabledValue( attrs?.add_image_caption?.innerContent?.desktop?.value ) &&
				<div>
					<FieldContainer
						attrName="image_caption_position.innerContent"
						label={ __('Image Caption Position', 'jet-engine-divi-views') }
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'after',
									label: __( 'After' ),
								},
								{
									value: 'before',
									label: __( 'Before' ),
								},
							] ) }
						/>
					</FieldContainer>

					<FieldContainer
						attrName="image_caption.innerContent"
						label={ __('Image Caption Text', 'jet-engine-divi-views') }
						description={ __('', 'jet-engine-divi-views') }
					>
						<TextContainer/>
					</FieldContainer>
				</div>
			}
		</GroupContainer>
		<AdminLabelGroup
			defaultGroupAttr={defaultSettingsAttrs?.module?.meta?.adminLabel}
		/>
	</React.Fragment>
};
