// 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
} from '@divi/field-library';
import {
	type Module,
} from '@divi/types';
import { ListingCalendarAttrs } from './types';
import {
	convertSimpleOptions,
	buildDefaultInnerContent,
	buildDefaultAttrsPatch,
	getBlockDefaultsFromSchema,
	getEffectiveAttrValue,
	isToggleEnabled,
} from '../../utils';

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

const LISTING_CALENDAR_DEFAULTS_FALLBACK: Record<string, any> = {
	lisitng_id: '',
	group_by: 'post_date',
	group_by_key: '',
	allow_multiday: false,
	end_date_key: '',
	use_custom_post_types: false,
	custom_post_types: [],
	week_days_format: 'short',
	custom_start_from: false,
	start_from_month: '',
	start_from_year: '',
	show_posts_nearby_months: true,
	hide_past_events: false,
	allow_date_select: false,
	start_year_select: '1970',
	end_year_select: '2038',
	caption_layout: 'layout-1',
	custom_query: false,
	custom_query_id: '',
	posts_query: [],
	meta_query_relation: 'AND',
	tax_query_relation: 'AND',
	hide_widget_if: '',
	_block_id: '',
	_element_id: '',
	cache_enabled: false,
	max_cache: '12',
	cache_timeout: '60',
};

const LISTING_CALENDAR_SELECT_ATTRS = new Set( [
	'lisitng_id',
	'group_by',
	'week_days_format',
	'start_from_month',
	'caption_layout',
	'custom_query_id',
	'hide_widget_if',
] );

const LISTING_CALENDAR_TOGGLE_ATTRS = new Set( [
	'allow_multiday',
	'use_custom_post_types',
	'custom_start_from',
	'show_posts_nearby_months',
	'hide_past_events',
	'allow_date_select',
	'custom_query',
	'cache_enabled',
] );

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

	const {
		defaultSettingsAttrs,
		attrs
	} = props;

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

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

		const next = buildDefaultAttrsPatch( {
			attrs,
			defaults: getBlockDefaultsFromSchema( 'listingCalendar', LISTING_CALENDAR_DEFAULTS_FALLBACK ),
			toggleKeys: LISTING_CALENDAR_TOGGLE_ATTRS,
			selectKeys: LISTING_CALENDAR_SELECT_ATTRS,
		} );

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

	const calendarDefaults = getBlockDefaultsFromSchema( 'listingCalendar', LISTING_CALENDAR_DEFAULTS_FALLBACK );
	const getToggleDefaultAttr = ( key: string ) => {
		return buildDefaultInnerContent( {
			key,
			value: calendarDefaults[ key ],
			toggleKeys: LISTING_CALENDAR_TOGGLE_ATTRS,
			selectKeys: LISTING_CALENDAR_SELECT_ATTRS,
		} );
	};
	const getAttrValue = ( key: string ) => getEffectiveAttrValue( {
		attrs,
		key,
		defaults: calendarDefaults,
		toggleKeys: LISTING_CALENDAR_TOGGLE_ATTRS,
		selectKeys: LISTING_CALENDAR_SELECT_ATTRS,
	} );

	return <React.Fragment>
		<GroupContainer
			id="general"
			title={__('General', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="lisitng_id.innerContent"
				label={__('Listing', 'jet-engine-divi-views')}
				description={__('Select a base listing item', 'jet-engine-divi-views')}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.listingOptions ) }
				/>
			</FieldContainer>
			<FieldContainer
				attrName="group_by.innerContent"
				label={__('Group posts by', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.calendarGroupKeys ) }
				/>
			</FieldContainer>
				{ 'meta_date' === getAttrValue( 'group_by' ) &&
					<>
						<FieldContainer
							attrName="group_by_key.innerContent"
							label={ __('Meta field name', 'jet-engine-divi-views') }
							description={ __('This field must contain date to group posts by. Works only if "Save as timestamp" option for meta field is active', 'jet-engine-divi-views') }
						>
						<TextContainer/>
					</FieldContainer>
					<FieldContainer
							attrName="allow_multiday.innerContent"
							label={ __('Allow multi-day events', 'jet-engine-divi-views') }
							description={''}
							defaultAttr={ getToggleDefaultAttr( 'allow_multiday' ) }
						>
							<ToggleContainer />
						</FieldContainer>
						{ isToggleEnabled( getAttrValue( 'allow_multiday' ) ) &&
							<FieldContainer
								attrName="end_date_key.innerContent"
							label={ __('End date field name', 'jet-engine-divi-views') }
							description={ __('This field must contain date when events ends. Works only if "Save as timestamp" option for meta field is active', 'jet-engine-divi-views') }
						>
							<TextContainer/>
						</FieldContainer>
					}
				</>
			}
				<FieldContainer
					attrName="use_custom_post_types.innerContent"
					label={ __('Use Custom Post Types', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'use_custom_post_types' ) }
				>
					<ToggleContainer />
				</FieldContainer>
				{ isToggleEnabled( getAttrValue( 'use_custom_post_types' ) ) &&
					<FieldContainer
						attrName="custom_post_types.innerContent"
					label={__('Post types', 'jet-engine-divi-views')}
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( window.JetEngineDiviViews.postTypes ) }
					/>
				</FieldContainer>
			}
			<FieldContainer
				attrName="week_days_format.innerContent"
				label={__('Week days format', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: 'full',
							label: __( 'Full' ),
						},
						{
							value: 'short',
							label: __( 'Short' ),
						},
						{
							value: 'initial',
							label: __( 'Initial letter' ),
						}
					] ) }
				/>
			</FieldContainer>
				<FieldContainer
					attrName="custom_start_from.innerContent"
					label={ __('Start from custom month', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'custom_start_from' ) }
				>
					<ToggleContainer />
				</FieldContainer>

				{ isToggleEnabled( getAttrValue( 'custom_start_from' ) ) &&
					<>
					<FieldContainer
						attrName="start_from_month.innerContent"
						label={__('Start from month', 'jet-engine-divi-views')}
						description={''}
					>
						<SelectContainer
							options={ convertSimpleOptions( [
								{
									value: 'January',
									label: __( 'January' ),
								},
								{
									value: 'February',
									label: __( 'February' ),
								},
								{
									value: 'March',
									label: __( 'March' ),
								},
								{
									value: 'April',
									label: __( 'April' ),
								},
								{
									value: 'May',
									label: __( 'May' ),
								},
								{
									value: 'June',
									label: __( 'June' ),
								},
								{
									value: 'July',
									label: __( 'July' ),
								},
								{
									value: 'August',
									label: __( 'August' ),
								},
								{
									value: 'September',
									label: __( 'September' ),
								},
								{
									value: 'October',
									label: __( 'October' ),
								},
								{
									value: 'November',
									label: __( 'November' ),
								},
								{
									value: 'December',
									label: __( 'December' ),
								},
							] ) }
						/>
					</FieldContainer>
					<FieldContainer
						attrName="start_from_year.innerContent"
						label={ __('Start from year', 'jet-engine-divi-views') }
						description={ '' }
					>
						<TextContainer/>
					</FieldContainer>
				</>
			}

				<FieldContainer
					attrName="show_posts_nearby_months.innerContent"
					label={ __('Show posts from the nearby months', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'show_posts_nearby_months' ) }
				>
					<ToggleContainer />
				</FieldContainer>
				<FieldContainer
					attrName="hide_past_events.innerContent"
					label={ __('Hide past events', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'hide_past_events' ) }
				>
					<ToggleContainer />
				</FieldContainer>
				<FieldContainer
					attrName="allow_date_select.innerContent"
					label={ __('Allow date select', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'allow_date_select' ) }
				>
					<ToggleContainer />
				</FieldContainer>

				{ isToggleEnabled( getAttrValue( 'allow_date_select' ) ) &&
					<>
						{ ! isToggleEnabled( getAttrValue( 'hide_past_events' ) ) &&
							<FieldContainer
							attrName="start_year_select.innerContent"
							label={__('Min select year', 'jet-engine-divi-views')}
							description={''}
						>
							<TextContainer/>
						</FieldContainer>
					}

					<FieldContainer
						attrName="end_year_select.innerContent"
						label={ __('Max select year', 'jet-engine-divi-views') }
						description={ __( 'You may use JetEngine macros in min/max select year. Also, you may use strings like \'+3years\', \'-1year\', \'this year\' to set year value relative to the curent year.' ) }
					>
						<TextContainer/>
					</FieldContainer>
				</>
			}

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

				{ isToggleEnabled( getAttrValue( 'cache_enabled' ) ) &&
					<>
					<FieldContainer
						attrName="cache_timeout.innerContent"
						label={ __('Cache Timeout', 'jet-engine-divi-views') }
						description={ __( 'Cache timeout in seconds. Set -1 for unlimited.' ) }
					>
						<TextContainer/>
					</FieldContainer>
					<FieldContainer
						attrName="max_cache.innerContent"
						label={ __('Maximum Cache Size', 'jet-engine-divi-views') }
						description={ __( 'Maximum cache size (months). If number of cached month exceeds this number - the oldest month will be deleted from cache.' ) }
					>
						<TextContainer/>
					</FieldContainer>
				</>
			}

			<FieldContainer
				attrName="caption_layout.innerContent"
				label={__('Caption Layout', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( [
						{
							value: 'layout-1',
							label: __( 'Layout 1' ),
						},
						{
							value: 'layout-2',
							label: __( 'Layout 2' ),
						},
						{
							value: 'layout-3',
							label: __( 'Layout 3' ),
						},
						{
							value: 'layout-4',
							label: __( 'Layout 4' ),
						},

					] ) }
				/>
			</FieldContainer>
		</GroupContainer>
		<GroupContainer
			id="custom-query"
			title={__('Custom Query', 'jet-engine-divi-views')}
		>
				<FieldContainer
					attrName="custom_query.innerContent"
					label={ __('Use Custom Query', 'jet-engine-divi-views') }
					description={''}
					defaultAttr={ getToggleDefaultAttr( 'custom_query' ) }
				>
					<ToggleContainer />
				</FieldContainer>

				{ isToggleEnabled( getAttrValue( 'custom_query' ) ) &&
					<FieldContainer
					attrName="custom_query_id.innerContent"
					label={__('Custom Query', 'jet-engine-divi-views')}
					description={''}
				>
					<SelectContainer
						options={ convertSimpleOptions( window.JetEngineDiviViews.queriesList ) }
					/>
				</FieldContainer>
			}
		</GroupContainer>
		<GroupContainer
			id="block-visibility"
			title={__('Block Visibility', 'jet-engine-divi-views')}
		>
			<FieldContainer
				attrName="hide_widget_if.innerContent"
				label={__('Hide block if', 'jet-engine-divi-views')}
				description={''}
			>
				<SelectContainer
					options={ convertSimpleOptions( window.JetEngineDiviViews.hideOptions || [] ) }
				/>
			</FieldContainer>
		</GroupContainer>
		<AdminLabelGroup
			defaultGroupAttr={defaultSettingsAttrs?.module?.meta?.adminLabel}
		/>
	</React.Fragment>
};
