import React, { useEffect, useState } from "react";
import {
	materialRenderers,
	materialCells
} from "@jsonforms/material-renderers";
import { JsonForms } from "@jsonforms/react";

const ENDPOINT = "https://cloudui.fastgenapp.com/forms";

export const TestForm = ({ id, onChange, defaultValues }) => {
	const [formSchema, setFormSchema] = useState(null);
	const [uiSchema, setUiSchema] = useState(null);
	const [initialData, setInitialData] = useState(defaultValues ?? null);

	useEffect(() => {
		fetchFormData();
	}, []);

	const handleChange = (data, errors) => {
		if (onChange) {
			onChange(data, errors);
		}
	};

	const fetchFormData = async () => {
		const response = await fetch(ENDPOINT + "/" + id);
		const data = (await response.json()).data;
		if (Object.hasOwnProperty.call(data, "formSchema")) {
			setFormSchema(data.formSchema);
		}
		if (Object.hasOwnProperty.call(data, "uiSchema")) {
			setUiSchema(data.uiSchema);
		}
		if (Object.hasOwnProperty.call(data, "defaultValues")) {
			setInitialData(data.defaultValues);
		}
	};
	return formSchema ? (
		<JsonForms
			schema={formSchema}
			uischema={uiSchema}
			data={initialData}
			renderers={materialRenderers}
			cells={materialCells}
			onChange={handleChange}
		/>
	) : (
		<div>Loading...</div>
	);
};
