import { useEffect, useState } from "react";
import { CircularProgress } from "@mui/material";
import { useForm } from "@refinedev/core";
import { UiSchema } from "@rjsf/utils";
import { jsonschemaProvider } from "../providers/jsonschema-provider";
import { BaseForm } from "./base-form";

type CrudFormProps = {
  schemaName: string,
  uiSchema?: UiSchema,
  resourceBasePath?: string,
  resource: string,
  id?: string,
  onSuccess?: (data: any) => void,
  defaultValue?: any
}

export const CrudForm: React.FC<CrudFormProps> = (props) => {
  const { schemaName, uiSchema, resourceBasePath="" ,resource, id, onSuccess, defaultValue } = props;

  const { onFinish, query, formLoading } = useForm({
    resource: resourceBasePath == "" ? resource : `${resourceBasePath}/${resource}`,
    action: id === undefined ? "create" : "edit",
    redirect: "show",
    id,
    onMutationSuccess: (data: any) => { if (onSuccess) { onSuccess(data) } },
  });

  const [schema, setSchema] = useState({});
  const [schemaLoading, setSchemaLoading] = useState(true);
  useEffect(() => {
    const fetchSchema = async () => {
      try {
        const schemaFullName = id === undefined ? `${schemaName}Create` : `${schemaName}Update`;
        const resourceSchema = await jsonschemaProvider.getResourceSchema(schemaFullName);
        setSchema(resourceSchema);
        setSchemaLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
        setSchemaLoading(false);
      }
    };
    fetchSchema();
  }, []);

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

  const record = query?.data?.data || defaultValue;
  return (
    <BaseForm
      schema={schema}
      uiSchema={uiSchema}
      formData={record}
      resourceBasePath={resourceBasePath}
      onSubmit={
        (data: any) => onFinish(data)
      }
    />
  )
}
