import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Icon } from '../icon/Icon';

const propTypes = {
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  className: PropTypes.string,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  isInline: PropTypes.bool,
  /**
   * Object of props passed to the button hide/show
   */
  buttonProps: PropTypes.object,
};

const defaultProps = {
  tag: 'div',
  className: '',
  defaultClassName: 'sui-a-form-control',
  isInline: false,
  buttonProps: {},
};

export const FormPassword = ({
  tag: Tag,
  defaultClassName,
  className,
  isInline,
  buttonProps,
  ...attributes
}) => {
  const [isPasswordShown, setIsPasswordShown] = useState(false);
  const classes = classnames(
    defaultClassName,
    className,
    isInline ? 'as--inline' : '',
  );

  return (
    <Tag className="sui-a-form-password">
      <input
        className={classes}
        {...attributes}
        type={isPasswordShown ? 'text' : 'password'}
      />
      <button
        onClick={() => setIsPasswordShown(!isPasswordShown)}
        type="button"
        className="sui-a-form-password__button"
        aria-label={isPasswordShown ? 'Hide password' : 'Show password'}
        {...buttonProps}
      >
        <Icon name={isPasswordShown ? 'fa-eye' : 'fa-eye-slash'} data-testid="icon-password" />
      </button>
    </Tag>
  );
};

FormPassword.propTypes = propTypes;
FormPassword.defaultProps = defaultProps;
