import React, { useState } from 'react';
import PropTypes from 'prop-types';

import { TextField } from '@/mui/components';

import styles from './TextFieldCell.module.scss';

function TextFieldCell({
  validate = null,
  id = null,
  stopRefreshInterval = null,
  resetRefreshInterval = null,
  disabled = false,
  ...props
}) {
  const [value, setValue] = useState(null);

  const handleChange = (e) => {
    if (validate) {
      const newValue = validate(e.target.value);
      if (newValue !== null) {
        setValue(newValue);
        if (newValue !== '') {
          props.onChange({ value: newValue, id });
        }
      }
    } else {
      setValue(e.target.value);
      props.onChange(e.target.value);
    }
  };

  return (
    <TextField
      id="textfield"
      className={styles.TextField}
      value={value === null ? props.cell : value}
      onChange={handleChange}
      onClick={(e) => {
        e.stopPropagation();
        e.preventDefault();
      }}
      onFocus={() => {
        if (stopRefreshInterval) {
          stopRefreshInterval();
        }
        setValue(props.cell);
      }}
      onBlur={() => {
        if (resetRefreshInterval) {
          resetRefreshInterval();
        }
        setValue(null);
      }}
      variant="outlined"
      size="small"
      disabled={disabled}
    />
  );
}

TextFieldCell.propTypes = {
  cell: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  validate: PropTypes.func,
  id: PropTypes.string,
  stopRefreshInterval: PropTypes.func,
  resetRefreshInterval: PropTypes.func,
  disabled: PropTypes.bool,
};

export default TextFieldCell;
