import React, { useState, useEffect, useMemo, 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,
 CssBaseline,
 Dialog,
 DialogContent,
 DialogContentText,
 Stack,
 ThemeProvider,
 CircularProgress,
} from '@mui/material';
import CommonSkeleton from '../renderers/common/Skeleton';
import { useImpaktAppsJsonFormsStore } from '../renderers/context/useImpaktappsJsonformsStore';
import { impaktappsJsonformsPropsType } from '../renderers/interface/inputfieldProps';
import { useTheme } from '../styles/StyleFactory';
import { createCustomAjv } from './App/Home';
import { v4 as uuid } from 'uuid';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

function AppWithoutRouter({
 serviceHolder,
 permissions,
 styleTheme,
 validationMode,
 navigationHolder,
 serverDateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ',
 locale,
 timeZone = 'Asia/Kolkata',
 dateFormat = 'YYYY-MM-DD',
 dateTimeFormat = 'YYYY-MM-DD HH:mm:ss',
 additionalIcons = {},
 notificationAutoHideDuration = 700,
 errorMap = {},
}: impaktappsJsonformsPropsType) {
 const [loading, setLoading] = useState(false);
 const [formKey, setFormKey] = useState(uuid());
 const pageInit = useRef(true);
 const theme = useTheme(styleTheme);
 const impaktAppsJsonFormsStore = useImpaktAppsJsonFormsStore(
  serviceHolder,
  validationMode,
  'RouterUnavailable',
  theme,
  loading,
  setLoading,
  permissions,
  navigationHolder,
  serverDateTimeFormat,
  dateFormat,
  dateTimeFormat,
  locale,
  timeZone,
  additionalIcons,
  notificationAutoHideDuration,
 );
 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, navigationHolder?.location]);
 const ajv = createCustomAjv();
 const createTranslator = (locale: any) => (key: any, defaultMessage: any) => {
  return errorMap[key] ?? defaultMessage;
 };

 const translation = useMemo(() => createTranslator(locale), [locale]);
 return (
  <ThemeProvider theme={theme.myTheme}>
   <CssBaseline />
   <DndProvider backend={HTML5Backend}>
    {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}
        i18n={{ locale: locale, translate: translation }}
       />
       <Dialog
        open={loading}
        PaperProps={{
         sx: {
          backgroundColor: 'transparent',
          boxShadow: 'none',
         },
        }}
       >
        <DialogContent>
         <DialogContentText>
          <Stack
           direction={'row'}
           sx={{
            alignItems: 'center',
           }}
          >
           <CircularProgress />
          </Stack>
         </DialogContentText>
        </DialogContent>
       </Dialog>
      </Box>
     </DataProvider>
    ) : (
     <CommonSkeleton />
    )}
   </DndProvider>
  </ThemeProvider>
 );
}

export default AppWithoutRouter;
