import { memo, useContext, useEffect, useState } from 'react';
import { IconButton, InputAdornment, TextField, Tooltip } from '@mui/material';
import { DataContext } from '../context/Context';
import ComponentWrapper from '../common/ComponentWrapper';
import { getFieldName } from '../permissions/getFieldName';
import { inputProps } from '../interface/inputfieldProps';
import { useDebouncedChange } from '@jsonforms/material-renderers';
import { Close } from '@mui/icons-material';
import { getComponentProps } from '../common/getComponentProps';
import _ from 'lodash';
import {
 formatAndMaskingProvider,
 prepareMaskingAndFormating,
} from '../common/formattingAndMasking';
import { ButtonIcon } from '../common/ButtonIcon';
import { useJsonForms } from '@jsonforms/react';
import React from 'react';
const Input = memo(function (props: inputProps) {
 const {
  data,
  required,
  errors,
  enabled,
  uischema,
  path,
  handleChange,
  schema,
  rootSchema,
 } = props;
 const uischemaData = uischema?.config?.main;
 const [showAdornment, setShowAdornment] = useState(false);
 const [actualValue, setActualValue] = useState('');
 const [count, setCount] = useState(0);
 const [maskedValue, setMaskedValue] = useState('');
 const { pageName, permissions, theme, serviceProvider } =
  useContext(DataContext);
 const fieldName = getFieldName(path);
 const eventToValue = (ev: any) =>
  ev.target.value === '' ? undefined : ev.target.value;
 const [inputText, onChange, onClear] = useDebouncedChange(
  handleChange,
  '',
  data,
  path,
  eventToValue,
 );

 const computedProps = getComponentProps(
  `${pageName}:${fieldName}`,
  permissions,
  schema,
  rootSchema,
 );
 const onPointerEnter = () => {
  if (!computedProps.disabled) {
   setShowAdornment(true);
  }
 };
 const onPointerLeave = () => setShowAdornment(false);
 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 };
 useEffect(() => {
  if (data && uischemaData.formatStrArray && count === 0) {
   const { updatedMaskedValue, isValidInput } = prepareMaskingAndFormating(
    data.split(''),
    uischemaData.formatStrArray,
   );
   if (isValidInput) {
    setCount(1);
    setMaskedValue(updatedMaskedValue);
    setActualValue(data);
   }
  }
 }, [data]);
 const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
  if (uischemaData.formatStrArray) {
   const { key, target } = event;
   const { isValidInput, updatedMaskedValue, updatedActualStr } =
    formatAndMaskingProvider(
     key,
     target,
     uischemaData.formatStrArray,
     actualValue,
    );
   if (isValidInput) {
    setActualValue(updatedActualStr);
    handleChange(path, updatedActualStr);
    setMaskedValue(updatedMaskedValue);
   }
  }
 };
 const handleInputChange = (
  e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
 ) => {
  if (!uischemaData.formatStrArray) {
   onChange(e);
  }
 };

 return (
  <ComponentWrapper
   {...getComponentProps(
    `${pageName}:${fieldName}`,
    permissions,
    schema,
    rootSchema,
   )}
  >
   <Tooltip
    title={uischemaData?.toolTip || ''}
    placement={uischemaData?.toolTipPosition || 'top'}
    arrow
   >
    <TextField
     id={uischemaData?.id}
     name={uischemaData.name}
     autoComplete={uischemaData.autoComplete}
     key={path}
     required={required}
     autoFocus={uischemaData?.autoFocus}
     fullWidth
     sx={{
      ...theme.InputFieldStyle,
      ...(computedProps.disabled && {
       '& .MuiOutlinedInput-root.Mui-disabled': {
        borderRadius: '12px',
       },
       '& .MuiOutlinedInput-input.Mui-disabled': {
        WebkitTextFillColor: theme.myTheme.palette?.disabled?.text,
       },
      }),
      ...componentStyle,
     }}
     value={uischemaData?.formatStrArray ? maskedValue : inputText}
     onKeyDown={(e) => handleKeyDown(e)}
     onChange={(e) => {
      handleInputChange(e);
     }}
     multiline={uischemaData?.multiline || false}
     placeholder={uischemaData?.placeholder}
     onPointerEnter={(event) => onPointerEnter()}
     onPointerLeave={(event) => onPointerLeave()}
     label={uischemaData?.label}
     size={uischemaData?.size || 'medium'}
     type={uischemaData?.type}
     variant={uischemaData?.variant}
     helperText={
      errors !== '' && errors.includes('pattern')
       ? uischemaData?.errorMessage
       : errors || '\u00A0'
     }
     error={errors !== '' ? true : false}
     slotProps={{
      inputLabel: {
       sx: {
        ...componentStyle.inputLabelStyle,
       },
      },
      input: {
       startAdornment: uischemaData?.startIcon ? (
        <InputAdornment position='start'>
         {ButtonIcon(uischemaData?.startIcon, uischemaData)}
        </InputAdornment>
       ) : null,
       endAdornment: (
        <InputAdornment
         position='end'
         style={{
          display:
           !showAdornment ||
           !enabled ||
           data === undefined ||
           uischemaData?.hideEndAdornment ||
           uischemaData?.type == 'number'
            ? 'none'
            : 'flex',
          position: 'absolute',
          right: 0,
         }}
        >
         <IconButton
          title='Clear'
          sx={{ color: theme.myTheme.palette.action.focus }}
          aria-label='Clear input field'
          onClick={() => {
           onClear();
           setMaskedValue('');
           setActualValue('');
          }}
          size='large'
         >
          <Close />
         </IconButton>
        </InputAdornment>
       ),
      },

      htmlInput: {
       ...uischemaData?.inputProps,
       style: { fontSize: theme.myTheme.typography.fontSize },
      },
     }}
    />
   </Tooltip>
  </ComponentWrapper>
 );
});

export default Input;
