import React from "react";
import { connect } from "react-redux";

import { IconAction } from "@ax/components";
import { ISite } from "@ax/types";
import { pageEditorActions } from "@ax/containers/PageEditor";
import { getNullValue } from "@ax/helpers";

import * as S from "./style";

const ArrayFieldInline = (props: IProps): JSX.Element => {
	const {
		fields,
		item,
		index,
		onChange,
		handleDelete,
		site,
		disabled,
		parentKey,
		actions,
		addComponentInArray,
		replaceModuleInArray,
	} = props;

	const deleteItem = () => handleDelete(index);

	const getFields = (fields: any[]): any[] => {
		return fields.map((field: any) => {
			const key = field.props.objKey;

			const handleChange = (newValue: any) => onChange({ [key]: newValue });

			const innerFields = field.props.innerFields ? getFields(field.props.innerFields) : undefined;
			const hasMultipleOptions = field.props.whiteList && field.props.whiteList.length > 1;

			const actionsField = {
				...actions,
				addComponentAction: (component: any, key: string) =>
					addComponentInArray(component, key, parentKey, index, hasMultipleOptions),
				replaceModuleAction: (module: string, parent: any, key: string) =>
					replaceModuleInArray(module, parent, key, parentKey, index),
			};

			const hideField = () => {
				const isContainer = field.props.type === "ComponentContainer";

				const nullValue = isContainer && item[key] ? getNullValue(item[key], hasMultipleOptions) : null;
				onChange({ [key]: nullValue });
			};

			return {
				...field,
				props: {
					...field.props,
					value: item[key],
					objKey: key,
					onChange: handleChange,
					innerFields,
					site,
					actions: actionsField,
					hideField,
				},
				key,
			};
		});
	};

	return (
		<S.Wrapper data-testid="arrayFieldInline">
			<S.Content>
				<S.IconWrapper>
					<IconAction icon="delete" onClick={deleteItem} size="s" disabled={disabled} />
				</S.IconWrapper>
				{getFields(fields)}
			</S.Content>
		</S.Wrapper>
	);
};

interface IProps {
	fields: any[];
	item: Record<string, unknown>;
	index: number;
	onChange: (value: Record<string, unknown>) => void;
	handleDelete: (index: number) => void;
	site: ISite | null;
	disabled?: boolean;
	parentKey: string;
	actions: any;
	addComponentInArray(type: string, key: string, parentKey: string, index: number, isMultiple: boolean): void;
	replaceModuleInArray(module: string, parent: any, key: string, parentKey: string, index: number): void;
}

const mapDispatchToProps = {
	addComponentInArray: pageEditorActions.addComponentInArray,
	replaceModuleInArray: pageEditorActions.replaceModuleInArray,
};

export default connect(null, mapDispatchToProps)(ArrayFieldInline);
