import {useEffect, useState, useCallback, useMemo, forwardRef} from '@wordpress/element';
import Section from './Section';

const storageKey = 'adpresso_modal_section_states';
// Load section state from session storage to open/close sections like they've been before.
const loadSectionState = ( key ) => {
	try {
		const raw = window.sessionStorage.getItem( key );
		return raw ? JSON.parse( raw ) : null;
	} catch { return null; }
};

// Save the section state
const saveSectionState = ( key, stateObj ) => {
	try {
		window.sessionStorage.setItem( key, JSON.stringify( stateObj ) );
	} catch {}
};

const SectionRenderer = forwardRef( ( {sections, allMetaData, onDataChange, availableConditions, entityData, i18n, onSetDirty}, ref ) => {
	const [dependentFields, setDependentFields] = useState( [] );
	const [collapsedStates, setCollapsedStates] = useState( null );

	const onToggleSection = useCallback( ( id ) => {
		setCollapsedStates( prev => {
			const next = {...prev, [id]: !prev[id]};
			saveSectionState( storageKey, next );
			return next;
		} );
	}, [] );

	useEffect( () => {
		const cached = loadSectionState( storageKey ) || {};
		const initial = {};
		const isUpdate = entityData && entityData.id !== 0;

		(sections || []).filter( Boolean ).forEach( sec => {
			// Open all sections by default.
			// Close the ad type section if we are in the update modal.
			const defaultCollapsed = sec.id === 'adpresso_ad_type' && isUpdate;

			initial[sec.id] = cached.hasOwnProperty( sec.id ) ? !!cached[sec.id] : defaultCollapsed;
		} );

		setCollapsedStates( initial );
	}, [sections, entityData?.id, storageKey] );

	const handleAdTypeChange = useCallback( ( fieldId, newValue, metaKey ) => {
		onDataChange( fieldId, newValue, metaKey );
		setCollapsedStates( prev => {
			const next = {...prev, adpresso_ad_content: false};
			saveSectionState( storageKey, next );
			return next;
		} );
	}, [onDataChange] );

	if ( !sections || sections.length === 0 ) {
		return null;
	}

	if ( !collapsedStates ) {
		return null;
	}

	return (
		<div className="adpresso-modal-sections">
			{sections.map( section => {
				const isAdTypeSection = section.fields?.some( f => f.type === 'image_group' );
				const sectionProps = {
					entityData:          entityData,
					key:                 section.id,
					section:             section,
					allMetaData:         entityData.meta_data,
					onDataChange:        isAdTypeSection ? handleAdTypeChange : onDataChange,
					availableConditions: availableConditions,
					i18n:                i18n,
					isCollapsed:         collapsedStates[section.id] ?? true,
					onToggleSection:     onToggleSection,
					sectionId:           section.id,
					ref:                 ref,
					onSetDirty:          onSetDirty
				};

				if ( section.controls_dependencies === true ) {
					sectionProps.setDependentFields = setDependentFields;
				}

				if ( section.receives_dependencies === true ) {
					sectionProps.injectedFields = dependentFields;
				}

				return <Section {...sectionProps} />;
			} )}
		</div>
	);
} );

export default SectionRenderer;
