import React, { useState, useEffect, useRef } from "react";
import { JsonForms, useJsonForms } from "@jsonforms/react";
import { materialCells } from "@jsonforms/material-renderers";
import renderers from "../../renderers";
import { DataProvider } from "../../renderers/context/Context";
import {
  Box,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogContentText,
  Stack,
} from "@mui/material";
import CommonSkeleton from "../../renderers/common/Skeleton";
import { useImpaktAppsJsonFormsStore } from "./../../renderers/context/useImpaktappsJsonformsStore";
import { HomePropsType } from "../../renderers/interface/inputfieldProps";
import { useLocation } from "react-router-dom";
import _ from "lodash";
import { v4 as uuid } from "uuid";
import Ajv from "ajv";

export const createCustomAjv = () => {
  const ajv = new Ajv({ allErrors: true, strict: false });
  ajv.removeKeyword("oneOf");
  ajv.addKeyword({
    validate: () => true,
    keyword: "oneOf",
  });
  return ajv;
};
function Home({
  serviceHolder,
  theme,
  permissions,
  validationMode,
  pageName,
  serverDateTimeFormat,
  dateFormat,
  dateTimeFormat,
  locale,
  timeZone,
  additionalIcons,
  notificationAutoHideDuration,
}: HomePropsType) {
  const [loading, setLoading] = useState(false);
  const [formKey, setFormKey] = useState(uuid());
  const location = useLocation();
  const impaktAppsJsonFormsStore = useImpaktAppsJsonFormsStore(
    serviceHolder,
    validationMode,
    pageName,
    theme,
    loading,
    setLoading,
    permissions,
    {},
    serverDateTimeFormat,
    dateFormat,
    dateTimeFormat,
    locale,
    timeZone,
    additionalIcons,
    notificationAutoHideDuration
  );
   const pageInit = useRef(true);
  const ctx = useJsonForms();
  const pageSetter = () => {
   impaktAppsJsonFormsStore.uiSchema && setLoading(true);
   sessionStorage.removeItem('pagemasterMetaData');
   const service = serviceHolder.getService(impaktAppsJsonFormsStore);
   service.setPage().then(() => {
    sessionStorage.removeItem('pageMasterInfo');
    impaktAppsJsonFormsStore.setValidation('ValidateAndHide');
    window.scrollTo(0, 0);
    setFormKey(uuid());
    setTimeout(() => {
     setLoading(false);
    }, 100);
   }).catch((err) => {
    console.error(err);
    setLoading(false); 
   });;
  };

 const changeHandler = (data: any, _errors: any) => {
  if (pageInit.current) {
     pageInit.current = false;
   return;
  }
  impaktAppsJsonFormsStore.updateFormdata(data);
  const service = impaktAppsJsonFormsStore.serviceHolder.getService(
   {
    ...impaktAppsJsonFormsStore,
    ctx,
   },
   { setLoading },
  );
  service?.onChange && service.onChange();
 };
  useEffect(() => {
    pageSetter();
  }, [impaktAppsJsonFormsStore.pageName, location]);
  const ajv = createCustomAjv();
  return (
    <div>
      {impaktAppsJsonFormsStore.uiSchema ? (
        <DataProvider impaktAppsJsonFormsStore={impaktAppsJsonFormsStore}>
          <Box
            sx={{
              ...theme.pageStyle,
              ...impaktAppsJsonFormsStore.uiSchema?.pageStyle,
            }}
          >
            <JsonForms
              key={formKey}
              data={impaktAppsJsonFormsStore.formData}
              schema={impaktAppsJsonFormsStore.schema}
              uischema={impaktAppsJsonFormsStore.uiSchema}
              renderers={renderers}
              cells={materialCells}
              onChange={({ data, errors }) => changeHandler(data, errors)}
              validationMode={impaktAppsJsonFormsStore.validationMode}
              additionalErrors={impaktAppsJsonFormsStore.additionalErrors}
              ajv={ajv}
            />

            <Dialog open={loading}>
              <DialogContent>
                <DialogContentText>
                  <Stack
                    direction={"row"}
                    spacing={2}
                    sx={{
                      alignItems: "center",
                    }}
                  >
                    <CircularProgress color="inherit" />
                    <Box sx={{}}>Fetching Data ...</Box>
                  </Stack>
                </DialogContentText>
              </DialogContent>
            </Dialog>
          </Box>
        </DataProvider>
      ) : (
        <CommonSkeleton />
      )}
    </div>
  );
}

export default Home;