import { ReactNode, 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,
  record?: any,
  resourceBasePath: string,
  onSubmit?: (data: any) => void,
  defaultValue?: any,
  children?: ReactNode
  card?: boolean
}

export const CrudForm: React.FC<CrudFormProps> = (props) => {
  const { schemaName, uiSchema, record, resourceBasePath, defaultValue, children, onSubmit=(data: any) => {}, card=false } = props;

  const [schema, setSchema] = useState({});
  const [schemaLoading, setSchemaLoading] = useState(true);
  useEffect(() => {
    const fetchSchema = async () => {
      try {
        let resourceSchema
        if (record === undefined) {
          resourceSchema = await jsonschemaProvider.getCreateResourceSchema(schemaName);
        } else {
          if (card) {
            resourceSchema = await jsonschemaProvider.getCardResourceSchema(schemaName);
          } else {
            resourceSchema = await jsonschemaProvider.getUpdateResourceSchema(schemaName);
          }
        }
        setSchema(resourceSchema);
        setSchemaLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
        setSchemaLoading(false);
      }
    };
    fetchSchema();
  }, []);

  if(schemaLoading) {
    return <CircularProgress />
  }

  return (
    <BaseForm
      schema={schema}
      uiSchema={uiSchema}
      formData={record || defaultValue}
      resourceBasePath={resourceBasePath}
      onSubmit={
        (data: any) => onSubmit(data)
      }
      children={children}
    />
  )
}
