import { Tabs } from "@ax/components";
import type { IErrorItem, ISchema, ISchemaField, ISchemaTab } from "@ax/types";

import ConnectedField from "./ConnectedField";

import * as S from "./style";

export const Form = (props: IFormProps): JSX.Element => {
	const {
		schema,
		selectedTab,
		actions,
		isGlobal,
		theme,
		headerHeight,
		errors,
		isDisabled,
		setSelectedTab,
		setHistoryPush,
		setErrors,
	} = props;

	const tabContent = schema.configTabs.find((tab: ISchemaTab) => tab.title.toLowerCase() === selectedTab);
	const setTab = (tab: string) => setSelectedTab(tab);

	const generateFields = (field: ISchemaField) => {
		const { setSelectedContent } = props;
		const { key, whiteList } = field;

		const goTo = (editorID: number) => setSelectedContent(editorID);

		return (
			<ConnectedField
				selectedTab={selectedTab}
				whiteList={whiteList}
				key={key}
				objKey={key}
				field={field}
				goTo={goTo}
				actions={actions}
				componentType={schema.schemaType}
				isGlobal={isGlobal}
				theme={theme}
				setHistoryPush={setHistoryPush}
				errors={errors}
				setErrors={setErrors}
				isReadOnly={isDisabled}
			/>
		);
	};

	const getTabs = () => {
		const isPageSchema = schema.schemaType === "page";
		const mappedTabs = schema.configTabs.reduce((acc: string[], curr: ISchemaTab) => {
			const currTitle = curr.title.toLowerCase();
			if (!isPageSchema || currTitle === "content" || currTitle === "config") {
				return acc.concat(currTitle);
			}
			return acc;
		}, []);

		return mappedTabs;
	};

	const tabs = getTabs();

	return (
		<S.Wrapper data-testid="form-section">
			<S.TabsWrapper headerHeight={headerHeight}>
				<Tabs tabs={tabs} active={selectedTab} setSelectedTab={setTab} />
			</S.TabsWrapper>
			{tabContent?.fields.map((field: ISchemaField) => generateFields(field))}
		</S.Wrapper>
	);
};

export interface IFormProps {
	selectedTab: string;
	schema: ISchema | Record<string, never>;
	actions: any;
	setSelectedTab(tab: string): void;
	setSelectedContent(editorID: number): void;
	isGlobal?: boolean;
	theme: string;
	setHistoryPush?: (path: string, isEditor: boolean) => void;
	headerHeight: number;
	errors: IErrorItem[];
	setErrors(errors: IErrorItem[]): void;
	isDisabled: boolean;
}

export default Form;
