import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import { Check, Close, Edit } from '@mui/icons-material';

import { IconButton, TextField, Typography } from '@/mui/components';

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

function Name(props) {
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingValue, setEditingValue] = useState('');

  return (
    <div className={styles.Name}>
      <div
        className={classNames(styles.TextWrap, {
          [styles.TextWrap___editMode]: isEditMode,
        })}
      >
        <Typography
          className={classNames(styles.Text, {
            [styles.Text___hidden]: isEditMode,
          })}
          variant="h6"
          color="text.primary"
          fontWeight={400}
        >
          {props.isReadOnly ? `${props.name} (Read-Only)` : props.name}
        </Typography>

        {isEditMode && (
          <TextField
            className={styles.Textfield}
            data-id="name"
            value={editingValue}
            onChange={({ target }) => {
              setEditingValue(target.value.substring(0, 200));
            }}
            variant="outlined"
            size="medium"
          />
        )}
      </div>
      {!isEditMode && !props.isReadOnly && (
        <IconButton
          className={styles.IconButton}
          size="small"
          color="info"
          onClick={() => {
            setIsEditMode(true);
            setEditingValue(props.name);
          }}
        >
          <Edit />
        </IconButton>
      )}

      {isEditMode && !props.isReadOnly && (
        <>
          <IconButton
            className={styles.IconButton}
            size="small"
            onClick={() => {
              props.onChange(editingValue);
              setIsEditMode(false);
            }}
            disabled={!editingValue?.length}
          >
            <Check />
          </IconButton>
          <IconButton
            className={styles.IconButton}
            size="small"
            onClick={() => {
              setIsEditMode(false);
            }}
          >
            <Close />
          </IconButton>
        </>
      )}
    </div>
  );
}

Name.propTypes = {
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  isReadOnly: PropTypes.bool.isRequired,
};

export default Name;
