import React from "react";

import { getInnerFields } from "@ax/forms";
import { FieldContainer, FieldGroup } from "@ax/components";
import { IErrorItem, IPage, ISite, ILanguage } from "@ax/types";

const Field = (props: IFieldProps): JSX.Element => {
	const {
		whiteList,
		objKey,
		field,
		selectedContent,
		goTo,
		pages,
		actions,
		site,
		lang,
		disabled,
		readonly,
		updateValue,
		error,
		errors,
		theme,
		moduleCopy,
		template,
		setHistoryPush,
		languages,
		deleteError,
	} = props;

	const isGroup = field.type === "FieldGroup";
	const isCollapsed = isGroup && field.collapsed;
	const isConditional = field.type === "ConditionalField";
	const isArrayGroup = field.type === "ArrayFieldGroup";

	let innerFields: JSX.Element[] = [];

	if (isGroup || isConditional || isArrayGroup) {
		const innerActions = { ...actions, updateValue, goTo };
		innerFields = getInnerFields(
			field.fields,
			innerActions,
			selectedContent,
			true,
			theme,
			moduleCopy,
			disabled,
			site,
			errors,
		);
	}

	return isGroup ? (
		<FieldGroup title={field.title} collapsed={isCollapsed}>
			{innerFields}
		</FieldGroup>
	) : (
		<FieldContainer
			whiteList={whiteList}
			key={objKey}
			objKey={objKey}
			field={field}
			selectedContent={selectedContent}
			goTo={goTo}
			updateValue={updateValue}
			pages={pages}
			actions={actions}
			site={site}
			lang={lang}
			innerFields={innerFields}
			disabled={disabled}
			readonly={readonly}
			error={error}
			theme={theme}
			moduleCopy={moduleCopy}
			template={template}
			setHistoryPush={setHistoryPush}
			languages={languages}
			deleteError={deleteError}
		/>
	);
};

export interface IFieldProps {
	whiteList: any;
	objKey: string;
	field: any;
	selectedContent: any;
	goTo: any;
	pages: IPage[];
	actions: any;
	site?: ISite;
	lang?: number;
	disabled?: boolean;
	readonly?: boolean;
	updateValue: (key: string, value: any, templateID?: number, slugTo?: string) => void;
	error?: IErrorItem;
	errors: IErrorItem[];
	collapsed?: boolean;
	theme: string;
	moduleCopy: { date: string; element: Record<string, unknown> } | null;
	template: any;
	setHistoryPush?: (path: string, isEditor: boolean) => void;
	languages?: ILanguage[];
	deleteError(error: IErrorItem): void;
}

export default Field;
