import validator from "@rjsf/validator-ajv8";
import Form from "@rjsf/mui";
import {RegistryFieldsType, RegistryWidgetsType} from "@rjsf/utils";
import { useEffect, useState } from "react";
import { jsonschemaProvider } from "../../providers/jsonschema-provider";
import { useForm } from "@refinedev/core";
import CrudTextWidget from "./widgets/crud-text-widget";
import UnionEnumField from "./fields/union-enum";

type Props = {
    schemaName: string,
    resource: string,
    id?: string,
    //onSubmit: (data: IChangeEvent, event: FormEvent<any>) => void
}

const customWidgets: RegistryWidgetsType = {
  TextWidget: CrudTextWidget
};

const customFields: RegistryFieldsType = {
  AnyOfField: UnionEnumField
}

export const CrudForm: React.FC<Props> = ({schemaName, resource, id}) => {
  const { onFinish, query, formLoading } = useForm({
    resource: resource,
    action: id === undefined ? "create" : "edit",
    redirect: "show",
    id,
  });

  const record = query?.data?.data;
  const [formData, setFormData] = useState(record);

  const [schema, setSchema] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchSchema = async () => {
      try {
        const resourceSchema = await jsonschemaProvider.getResourceSchema(schemaName);
        setSchema(resourceSchema);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
        setLoading(false);
      }
    };
    fetchSchema();
  }, []);

  return (
    <Form
      schema={schema}
      formData={record}
      onChange={(e) => setFormData(e.formData)}
      onSubmit={(e) => onFinish(e.formData)}
      validator={validator}
      omitExtraData={true}
      widgets={customWidgets}
      fields={customFields}
    />
  )
}