// 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,
	UploadContainer,
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { DynamicLinkAttrs } 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_LINK_DEFAULTS_FALLBACK: Record<string, any> = {
	dynamic_link_source: '_permalink',
	dynamic_link_option: '',
	dynamic_link_profile_page: '',
	dynamic_link_source_custom: '',
	delete_link_dialog: 'Are you sure you want to delete this post?',
	delete_link_redirect: '',
	delete_link_type: 'trash',
	selected_link_icon: 0,
	selected_link_icon_url: '',
	link_label: '%title%',
	link_wrapper_tag: 'div',
	add_query_args: false,
	query_args: '',
	url_prefix: '',
	url_anchor: '',
	open_in_new: false,
	rel_attr: '',
	aria_label_attr: '',
	hide_if_empty: false,
	object_context: 'default_object',
	acf_field_key: '',
};

const DYNAMIC_LINK_SELECT_ATTRS = new Set( [
	'dynamic_link_source',
	'dynamic_link_option',
	'acf_field_key',
	'dynamic_link_profile_page',
	'delete_link_type',
	'link_wrapper_tag',
	'rel_attr',
	'object_context',
] );

const DYNAMIC_LINK_TOGGLE_ATTRS = new Set( [
	'add_query_args',
	'open_in_new',
	'hide_if_empty',
	'dynamic_link_synch_grid',
	'dynamic_link_enable_quantity_input',
	'remove_post_from_listing',
] );

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

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: getBlockDefaultsFromSchema( 'dynamicLink', DYNAMIC_LINK_DEFAULTS_FALLBACK ),
			toggleKeys: DYNAMIC_LINK_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_LINK_SELECT_ATTRS,
		} );

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

	const dynamicLinkDefaults = getBlockDefaultsFromSchema( 'dynamicLink', DYNAMIC_LINK_DEFAULTS_FALLBACK );
	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: dynamicLinkDefaults[ key ],
			toggleKeys: DYNAMIC_LINK_TOGGLE_ATTRS,
			selectKeys: DYNAMIC_LINK_SELECT_ATTRS,
		} );
	};

	const getAttrValue = ( key: keyof DynamicLinkAttrs, fallback: unknown = '' ): unknown => {
		return attrs?.[ key ]?.innerContent?.desktop?.value ?? fallback;
	};

	const customControls = window.JetEngineDiviViews?.customControls?.['dynamic-link'] || [];

	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="dynamic_link_source.innerContent"
				label={ __('Source', 'jet-engine-divi-views') }
				description={__('', 'jet-engine-divi-views')}
			>
				<SelectContainer
					options={ convertGroupedOptions( window.JetEngineDiviViews.linkFields ) }
				/>
			</FieldContainer>

			{ 'options_page' === getAttrValue( 'dynamic_link_source', '_permalink' ) &&
				<FieldContainer
					attrName="dynamic_link_option.innerContent"
					label={ __('Option', 'jet-engine-divi-views') }
					description={__('', 'jet-engine-divi-views')}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.optionsFields ) }
					/>
				</FieldContainer>
			}

			{ 'acf_field_groups' === getAttrValue( 'dynamic_link_source', '_permalink' ) && undefined !== window.JetEngineDiviViews.acfLinksFields &&
				<FieldContainer
					attrName="acf_field_key.innerContent"
					label={ __('ACF Field', 'jet-engine-divi-views') }
					description={__('', 'jet-engine-divi-views')}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.acfLinksFields ) }
					/>
				</FieldContainer>
			}

			{ 'profile_page' === getAttrValue( 'dynamic_link_source', '_permalink' ) && undefined !== window.JetEngineDiviViews.profileBuilderPages &&
				<FieldContainer
					attrName="dynamic_link_profile_page.innerContent"
					label={ __('Profile Page', 'jet-engine-divi-views') }
					description={__('', 'jet-engine-divi-views')}
				>
					<SelectContainer
						options={ convertGroupedOptions( window.JetEngineDiviViews.profileBuilderPages ) }
					/>
				</FieldContainer>
			}

			{ 'delete_post_link' !== getAttrValue( 'dynamic_link_source', '_permalink' ) &&
				<FieldContainer
					attrName="dynamic_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>
			}

			{ 'delete_post_link' === getAttrValue( 'dynamic_link_source', '_permalink' ) &&
				<div>
					<FieldContainer
						attrName="delete_link_dialog.innerContent"
						label={ __('Confirm deletion message', 'jet-engine-divi-views') }
						description={ __('Only users with appropriate permissions can delete posts', 'jet-engine-divi-views') }
					>
						<TextAreaContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="delete_link_redirect.innerContent"
						label={ __('Redirect after delete', 'jet-engine-divi-views') }
						description={ __('If empty will redirect to home page. Use the %current_page_url% macro to redirect to the current page.', 'jet-engine-divi-views') }
					>
						<TextContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="delete_link_type.innerContent"
						label={ __('Delete post type', 'jet-engine-divi-views') }
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'trash',
									label: __("Move to trash"),
								},
								{
									value: 'permanently',
									label: __("Delete permanently"),
								},
							] ) }
						/>
					</FieldContainer>
				</div>
			}

			{ customControls && customControls.length && customControls.map( ( control: any ) => {
				return <CustomControl
					control={ control }
					currentAttr={ control.name + '.innerContent' }
				/>;
			} ) }

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

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

			{ isToggleEnabledValue( attrs?.add_query_args?.innerContent?.desktop?.value ) &&
				<FieldContainer
					attrName="query_args.innerContent"
					label={ __('Query Arguments', 'jet-engine-divi-views') }
					description={ __('', 'jet-engine-divi-views') }
				>
					<TextAreaContainer/>
				</FieldContainer>
			}

			<FieldContainer
				attrName="url_prefix.innerContent"
				label={ __('URL Prefix (tel:, mailto: etc)', 'jet-engine-divi-views') }
				description={ __('', 'jet-engine-divi-views') }
			>
				<TextContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="url_anchor.innerContent"
				label={ __('URL Anchor', 'jet-engine-divi-views') }
				description={ __('Add anchor to the URL. Without #.', 'jet-engine-divi-views') }
			>
				<TextContainer/>
			</FieldContainer>

			<FieldContainer
				attrName="selected_link_icon_url.innerContent"
				label={__('Icon', 'jet-engine-divi-views')}
				description={__('', 'jet-engine-divi-views')}
				features={{
					sticky: false,
				}}
			>
				<UploadContainer />
			</FieldContainer>

			{ ! window.JetEngineDiviViews.preventWrap &&
				<FieldContainer
					attrName="link_wrapper_tag.innerContent"
					label={ __('HTML wrapper', 'jet-engine-divi-views') }
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( [
							{
								value: 'div',
								label: 'DIV',
							},
							{
								value: 'h1',
								label: 'H1',
							},
							{
								value: 'h2',
								label: 'H2',
							},
							{
								value: 'h3',
								label: 'H3',
							},
							{
								value: 'h4',
								label: 'H4',
							},
							{
								value: 'h5',
								label: 'H5',
							},
							{
								value: 'h6',
								label: 'H6',
							},
							{
								value: 'p',
								label: 'P',
							},
							{
								value: 'span',
								label: 'SPAN',
							},
						] ) }
					/>
				</FieldContainer>
			}

			<FieldContainer
				attrName="open_in_new.innerContent"
				label={ __('Open in new window', 'jet-engine-divi-views') }
				description={__('', 'jet-engine-divi-views')}
				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="aria_label_attr.innerContent"
				label={ __('Aria label attr', 'jet-engine-divi-views') }
				description={ __('', 'jet-engine-divi-views') }
			>
				<TextContainer/>
			</FieldContainer>

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

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

		</GroupContainer>

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