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

import { getComponentProps } from '../common/getComponentProps';
import _ from 'lodash';

const IconsButton = memo(function ({
 uischema,
 path,
 schema,
 rootSchema,
 data,
}: inputProps) {
 const [loading, setLoading] = useState(false);
 const { serviceProvider, pageName, permissions, theme, additionalIcons } =
  useContext(DataContext);
 const uischemaData = uischema?.config?.main;
 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 myIconComponent = ButtonIcon(
  data || uischemaData?.icon,
  uischema?.config,
  additionalIcons,
 );
 const myStyle = uischemaData?.styleDefault ? theme.IconStyle : {};
 const fieldName = getFieldName(path);
 const callServiceProvider = (event: any) => {
  serviceProvider(ctx, uischemaData, {
   event,
   path,
   ...uischemaData.additionalData,
   setLoading,
  });
 };
 return (
  <>
   <ComponentWrapper
    {...getComponentProps(
     `${pageName}:${fieldName}`,
     permissions,
     schema,
     rootSchema,
    )}
   >
    <IconButton
     sx={{
      ...myStyle,
      ...componentStyle,
     }}
     disableRipple={uischemaData?.disableRipple === false ? false : true}
     size={uischemaData?.size || 'medium'}
     color={uischemaData?.color ? uischemaData?.color : 'primary'}
     disabled={loading || uischemaData?.disabled}
     title={uischemaData?.tooltipMessage}
     onKeyDown={(e) => callServiceProvider(e)}
     onClick={(e) => callServiceProvider(e)}
     onPointerEnter={(event) => callServiceProvider(event)}
     onPointerLeave={(event) => callServiceProvider(event)}
     onFocus={(event) => callServiceProvider(event)}
     onBlur={(event) => callServiceProvider(event)}
     onMouseEnter={(event) => callServiceProvider(event)}
    >
     {myIconComponent}
    </IconButton>
   </ComponentWrapper>
   <LoaderInfo id={path} loading={loading} />
  </>
 );
});

export default IconsButton;
