import { FieldContainer, FieldGroup, FieldsBehavior } from "@ax/components";
import type { IErrorItem, IPage, ISite } from "@ax/types";

const getInnerFields = (
	innerFields: any[],
	innerActions: any,
	selectedContent: IPage,
	isTemplateActivated: boolean,
	theme: string,
	moduleCopy: { date: string; element: Record<string, unknown> } | null,
	parentDisabled?: boolean,
	site?: ISite,
	errors?: IErrorItem[],
	deleteError?: (error: IErrorItem) => void,
) => {
	let fieldArr: any[] = [];

	return innerFields?.map((singleFieldProps: any) => {
		const { key } = singleFieldProps;
		const error = errors?.find((err: any) => err.editorID === selectedContent.editorID && err.key === key);

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

		if (isGroup || isConditional || isArrayGroup) {
			fieldArr = getInnerFields(
				singleFieldProps.fields,
				innerActions,
				selectedContent,
				isTemplateActivated,
				theme,
				moduleCopy,
				parentDisabled,
				site,
				errors,
				deleteError,
			);
		}

		return isGroup ? (
			<FieldGroup key={key} title={singleFieldProps.title} collapsed={isCollapsed} solid={singleFieldProps.solid}>
				{fieldArr}
			</FieldGroup>
		) : (
			<FieldContainer
				key={key}
				objKey={key}
				innerFields={fieldArr}
				field={singleFieldProps}
				actions={innerActions}
				selectedContent={selectedContent}
				updateValue={innerActions.updateValue}
				goTo={innerActions.goTo}
				site={site}
				{...singleFieldProps}
				disabled={!isTemplateActivated || singleFieldProps.disabled || parentDisabled}
				error={error}
				deleteError={deleteError}
				theme={theme}
				moduleCopy={moduleCopy}
			/>
		);
	});
};

const getStructuredDataInnerFields = (
	innerFields: any[],
	content: any,
	updateValue: (value: Record<string, unknown>) => void,
	theme: string,
	errors: IErrorItem[],
) => {
	let fieldArr: any[] = [];

	return innerFields?.map((singleFieldProps: any) => {
		const { key, type, fields } = singleFieldProps;

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

		const value = content?.[key];

		if (type === "ConditionalField" || type === "ArrayFieldGroup") {
			fieldArr = getStructuredDataInnerFields(fields, content, updateValue, theme, errors);
		}

		const error = errors.find((err: any) => err.key === key);

		const fieldProps = {
			value,
			objKey: key,
			fieldType: type,
			innerFields: fieldArr,
			field: singleFieldProps,
			onChange: handleChange,
			...singleFieldProps,
			theme,
			error,
		};

		return <FieldsBehavior key={key} {...fieldProps} />;
	});
};

export { getInnerFields, getStructuredDataInnerFields };
