import validator from "@rjsf/validator-ajv8";
import Form from "@rjsf/mui";
import { RegistryFieldsType, RegistryWidgetsType, UiSchema } 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";
import { CircularProgress } from "@mui/material";
import { ResourceContext } from "../contexts/ResourceContext";

type CrudFormProps = {
  schemaName: string,
  uiSchema?: UiSchema,
  resource: string,
  resourceBasePath?: string,
  id?: string,
  //onSubmit: (data: IChangeEvent, event: FormEvent<any>) => void
  onSuccess?: (data: any) => void
}

const customWidgets: RegistryWidgetsType = {
  TextWidget: CrudTextWidget
};

const customFields: RegistryFieldsType = {
  AnyOfField: UnionEnumField
}

export const CrudForm: React.FC<CrudFormProps> = (props) => {
  const { schemaName, uiSchema, resourceBasePath="" ,resource, id, onSuccess } = props;
  const { onFinish, query, formLoading } = useForm({
    resource: `${resourceBasePath}/${resource}`,
    action: id === undefined ? "create" : "edit",
    redirect: "show",
    id,
    onMutationSuccess: (data: any) => { if (onSuccess) { onSuccess(data) } },
  });

  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();
  }, []);


  if(formLoading || loading) {
    return <CircularProgress />
  }

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