import { Error, ErrorProps } from './Error';
import { useLayoutDrawerState, useLayoutMediaState } from './Provider';
import { useThemeConfig } from '@/components/Layout/ThemeProvider';
import { Box, Container, Toolbar } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { Loading } from 'ra-ui-materialui';
import { ErrorInfo, Suspense, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

type ILayoutContentProps = React.PropsWithChildren & {
  error?: React.ComponentType<ErrorProps>;
};

function LayoutContent(props: ILayoutContentProps) {
  const { width } = useLayoutDrawerState();
  const { horizontal } = useLayoutMediaState();
  const { container, themeOrientation } = useThemeConfig();
  const [errorInfo, setErrorInfo] = useState<ErrorInfo | null>(null);
  function handleError(_: Error, info: ErrorInfo) {
    setErrorInfo(info);
  }
  const theme = useTheme();

  return (
    <ErrorBoundary
      onError={handleError}
      fallbackRender={({ error, resetErrorBoundary }) => (
        <Error
          error={error}
          errorComponent={props.error}
          errorInfo={errorInfo!}
          resetErrorBoundary={resetErrorBoundary}
        />
      )}
    >
      <Suspense fallback={<Loading />}>
        <Box
          component="main"
          sx={{ width: `calc(100% - ${width}px)`, flexGrow: 1, p: { xs: 0, sm: 2, lg: 1 }, pt: { lg: 2 } }}
        >
          <Toolbar sx={{ mt: horizontal ? 8 : 'inherit' }} /> {/*Hugh...*/}
          <Container
            maxWidth={container ? 'xl' : false}
            sx={{
              ...(container && { px: { xs: 0, sm: 2 } }),
              position: 'relative',
              minHeight: themeOrientation === 'horizontal' ? 'calc(100vh - 160px)' : 'calc(100vh - 110px)',
              display: 'flex',
              flexDirection: 'column',
              [theme.breakpoints.down('sm')]: {
                px: '12px'
              }
            }}
          >
            {props.children}
          </Container>
        </Box>
      </Suspense>
    </ErrorBoundary>
  );
}

export { LayoutContent };
