import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Text } from '../../atoms/text/Text';
import { useModalContext } from './Modal';

const propTypes = {
  className: PropTypes.string,
  confirmPhrase: PropTypes.string,
  onDelete: PropTypes.func,
  additionalProps: PropTypes.object,
};

const defaultProps = {
  className: 'sui-a-form-control sui-h-mb-md',
  confirmPhrase: '',
  onDelete: () => {},
  additionalProps: {},
};

export const ModalInput = ({
  className, confirmPhrase, onDelete, additionalProps,
}) => {
  const [inputValue, setInputValue] = useState('');
  const { handleClose, isOpen } = useModalContext();

  const handleInputChange = (e) => {
    const { value } = e.target;
    setInputValue(value);
  };

  const example = {
    cancel: {
      ...additionalProps.cancel,
    },
    delete: {
      ...additionalProps.delete,
      disabled: inputValue !== confirmPhrase || (
        additionalProps.delete ? additionalProps.delete.disabled : false),
    },
  };

  useEffect(() => {
    if (!isOpen) setInputValue('');
  },[isOpen])

  return (
    <>
      <Text className="sui-h-mv-md">{`Type "${confirmPhrase}" to confirm:`}</Text>
      <input className={className} value={inputValue} onChange={handleInputChange} />
      <Text color="danger" className="sui-h-mv-md">This operation cannot be undone.</Text>
      <div className="sui-g-grid">
        <div className="sui-g-grid__item as--pull">
          <button type="button" className="sui-a-button" onClick={handleClose} {...example.cancel}>
            Cancel
          </button>
        </div>
        <div className="sui-g-grid__item as--push">
          <button type="button" className="sui-a-button as--danger" onClick={onDelete} {...example.delete}>
            Delete
          </button>
        </div>
      </div>
    </>
  );
};

ModalInput.propTypes = propTypes;
ModalInput.defaultProps = defaultProps;
