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

const CheckBox = memo((props: inputProps) => {
 const { schema, rootSchema, uischema, data, handleChange, path } = props;
 const [checked, setChecked] = useState(!!data);
 const uischemaData = uischema?.config?.main;
 const { pageName, permissions, theme, serviceProvider } =
  useContext(DataContext);
 const fieldName = getFieldName(path);
 useEffect(() => {
  setChecked(!!data);
 }, [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 };
 return (
  <ComponentWrapper
   {...getComponentProps(
    `${pageName}:${fieldName}`,
    permissions,
    schema,
    rootSchema,
   )}
  >
   <FormControlLabel
    sx={{
     marginLeft: 0,
     marginRight: 0,
     ...componentStyle?.formControlLabel,
    }}
    key={`${uischemaData?.additionalData?.id || path}_CheckedControllerKey`}
    control={
     <Checkbox
      id={`${uischemaData?.additionalData?.id || path}_CheckedID`}
      key={`${uischemaData?.additionalData?.id || path}_CheckedKey`}
      onChange={(event) => {
       setChecked(event.target.checked);
       handleChange(path, event.target.checked);
      }}
      checked={checked}
      disableRipple={uischemaData?.disableRipple || true}
      checkedIcon={<Check />}
      size={uischemaData?.size || 'medium'}
      sx={{
       ...theme.CheckBoxStyle,
       ...componentStyle,
      }}
     />
    }
    slotProps={{
     typography: {
      style: {
       fontSize: theme.myTheme.typography.fontSize,
      },
     },
    }}
    label={uischema?.config?.main?.label}
   />
  </ComponentWrapper>
 );
});
export default memo(withJsonFormsControlProps(CheckBox));
