import validator from "@rjsf/validator-ajv8";
import Form from "@rjsf/mui";
import { RegistryFieldsType, RegistryWidgetsType, RJSFSchema, UiSchema } from "@rjsf/utils";
import CrudTextWidget from "./widgets/crud-text-widget";
import UnionEnumField from "./fields/union-enum";
import { ResourceContext } from "../contexts/ResourceContext";
import { ReactNode } from "react";

type BaseFormProps = {
  schema: RJSFSchema,
  resourceBasePath: string,
  onSubmit?: (data: any) => void,
  onChange?: (data: any) => void,
  uiSchema?: UiSchema,
  formData?: any,
  children?: ReactNode
}

export const customWidgets: RegistryWidgetsType = {
  TextWidget: CrudTextWidget
};

export const customFields: RegistryFieldsType = {
  AnyOfField: UnionEnumField
}

export const BaseForm: React.FC<BaseFormProps> = (props) => {
  const { schema, uiSchema, resourceBasePath, formData, children, onSubmit, onChange } = props;

  return (
    <ResourceContext.Provider value={{basePath: resourceBasePath}} >
      <Form
        schema={schema}
        uiSchema={uiSchema === undefined ? {} : uiSchema}
        formData={formData}
        onSubmit={(e, id) => onSubmit != undefined && onSubmit(e.formData)}
        validator={validator}
        omitExtraData={true}
        widgets={customWidgets}
        fields={customFields}
        onChange={(e, id) => onChange != undefined && onChange(e.formData)}
        children={children}
      />
    </ResourceContext.Provider>
  )
}
