import { useContext, useRef } from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { LocaleContext } from '@arcblock/ux/lib/Locale/context';
import commonPropTypes from './common-prop-types';
import { jsx as _jsx } from "react/jsx-runtime";
export default function TextInput({
  editing,
  description,
  value,
  onChange,
  componentProps = {},
  ...rest
}) {
  const {
    placeholder
  } = componentProps;
  const inputValue = useRef(value);
  const {
    t
  } = useContext(LocaleContext);

  // enter keydown
  const handleKeydown = e => {
    if (e.key === 'Enter') {
      onChange(inputValue.current, 'confirm');
    }
  };
  const onInputChange = changeValue => {
    inputValue.current = changeValue;
    onChange(changeValue);
  };
  if (editing) {
    return /*#__PURE__*/_jsx(TextField, {
      style: {
        flex: 1
      },
      fullWidth: true,
      value: value,
      onChange: e => {
        e.persist();
        onInputChange(e.target.value);
      },
      autoFocus: true,
      size: "small",
      variant: "outlined",
      placeholder: description || placeholder,
      onKeyDown: handleKeydown,
      ...rest
    });
  }
  return /*#__PURE__*/_jsx(Box, {
    className: "form-item-input slot",
    sx: {
      px: 1
    },
    children: !value ? /*#__PURE__*/_jsx("span", {
      className: "placeholder",
      children: t('common.requiredInputPlaceholder', {
        name: description || placeholder
      })
    }) : value
  });
}
TextInput.propTypes = commonPropTypes;