import { Modal, Panel, Button } from '@wordpress/components';
import { useCallback, useMemo, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

import InteractionSettings from './interaction-settings';

function defaultInteraction( id ) {
	return { id, on: 'none', fields: [] };
}

export default function InteractionsSettings( {
	interactions,
	setInteractions,
	sources,
	styleDefinition,
	onCloseModal,
} ) {
	const [ localInteractions, setLocalInteractions ] = useState( interactions );

	const interactiveLayers = useMemo( () => {
		if ( ! sources ) {
			return [];
		}

		let layersWithSource = styleDefinition.layers.filter( ( layer ) => {
			return layer.source && layer['source-layer'];
		} );

		layersWithSource = layersWithSource.map( ( layer ) => {
			const source = sources.find(( sourceLayer ) => sourceLayer.id === layer[ 'source-layer' ]);

			if(source) {
				layer.fields = source.fields;
				layer.source = source;
			} else {
				layer.fields = []
				layer.source = [];
			}

			return layer;
		} );

		return layersWithSource;
	}, [ sources, styleDefinition ] );


	const onInsert = useCallback(
		( newInteraction ) => {
			setLocalInteractions( [ ...localInteractions, newInteraction ] );
		},
		[ localInteractions, setLocalInteractions ]
	);

	const onUpdate = useCallback(
		( interactionId, newInteraction ) => {
			setLocalInteractions(
				localInteractions.map( ( interaction ) => {
					return interaction.id === interactionId
						? newInteraction
						: interaction;
				} )
			);
		},
		[ localInteractions, setLocalInteractions ]
	);

	const onDelete = useCallback(
		( interactionId ) => {
			setLocalInteractions(
				localInteractions.filter(
					( interaction ) => interaction.id !== interactionId
				)
			);
		},
		[ localInteractions, setLocalInteractions ]
	);

	const onDone = useCallback( () => {
		setInteractions( localInteractions );
		onCloseModal();
	}, [ localInteractions, setLocalInteractions ] );

	return (
		<Modal
			className="jeo-interactions-settings__modal"
			title={ __( 'Interactions', 'jeowp' ) }
			onRequestClose={ onDone }
		>
			<Panel className="jeo-interactions-settings">
				{ interactiveLayers.map( ( layer ) => {
					const index = localInteractions.findIndex(
						( x ) => x.id === layer.id
					);
					const interaction = localInteractions[ index ];
					return (
						<InteractionSettings
							key={ layer.id }
							interactionIndex={ index }
							interaction={ interaction || defaultInteraction( layer.id ) }
							layer={ layer }
							onInsert={ onInsert }
							onUpdate={ onUpdate }
							onDelete={ onDelete }
						/>
					);
					// }
				} ) }
			</Panel>
			<Button
				style={ { float: 'inline-start', margin: '8px 0' } }
				variant="primary"
				onClick={ onDone }
			>
				{ __( 'Done', 'jeowp' ) }
			</Button>
		</Modal>
	);
}
