import { memo, useContext, useEffect, useState } from 'react';
import { Box, Tooltip } from '@mui/material';
import { DataContext } from '../context/Context';
import { inputProps } from '../interface/inputfieldProps';
import { useJsonForms, withJsonFormsControlProps } from '@jsonforms/react';
import ComponentWrapper from '../common/ComponentWrapper';
import { getFieldName } from '../permissions/getFieldName';
import { getComponentProps } from '../common/getComponentProps';
import React from 'react';

const Image = memo(function ({
 uischema,
 path,
 data,
 schema,
 rootSchema,
}: inputProps) {
 const uischemaData = uischema?.config?.main;
 const [imageSrc, setImageSrc] = useState(data ? data : uischemaData?.url);
 const { pageName, permissions, theme, serviceProvider } =
  useContext(DataContext);
 const fieldName = getFieldName(path);
 useEffect(() => {
  setImageSrc(data ? data : uischemaData?.url);
 }, [data]);
 const ctx = useJsonForms();
 const dynamicStyle = React.useMemo(() => {
  return serviceProvider(
   ctx,
   {
    onClick: uischema.config?.main?.styleFunction || 'getStyle',
   },
   {
    event: { _reactName: 'onClick' },
    path,
   },
  );
 }, [data, path]);
 const componentStyle = { ...uischema.config?.style, ...dynamicStyle };
 const callServiceProvider = (event: any) => {
  serviceProvider(ctx, uischemaData, {
   event,
   path,
   ...uischemaData.additionalData,
  });
 };
 return (
  <ComponentWrapper
   {...getComponentProps(
    `${pageName}:${fieldName}`,
    permissions,
    schema,
    rootSchema,
   )}
  >
   <Tooltip
    title={uischemaData?.toolTip || ''}
    placement={uischemaData?.toolTipPosition || 'top'}
    arrow
   >
    <Box sx={{ ...componentStyle.containerStyle }}>
     <img
      src={imageSrc}
      alt='!'
      onClick={(e) => callServiceProvider(e)}
      onError={() =>
       setImageSrc('https://www.svgrepo.com/show/315818/unavailable.svg')
      }
      style={{
       ...theme?.BoxStyle,
       ...componentStyle?.imageStyle,
      }}
     />
    </Box>
   </Tooltip>
  </ComponentWrapper>
 );
});
export default withJsonFormsControlProps(Image);
