import React, { ReactElement, ChangeEvent, MouseEvent } from 'react';

import Button from '../Button';
import Icon from '../Icon';
import Input from '../Input';
import {
  Avatar,
  EditorContainer,
  EditorWrapper,
  EditorActionsWrapper,
} from './StyledComment';

export interface EditorProps {
  /**
   * Custom actions section, can be used for attaching file and more.
   */
  actions?: ReactElement;
  /**
   * Author avatar.
   */
  avatar?: string | ReactElement;
  /**
   * onChange event for Editor textarea.
   */
  onChange: (e: ChangeEvent) => void;
  /**
   * submit event.
   */
  onSubmit?: (e: MouseEvent) => void;
  /**
   * loading state for button.
   */
  submitting?: boolean;
  /**
   * content for text area.
   */
  value: string;
}

const Editor = ({
  avatar,
  onChange,
  onSubmit,
  submitting = false,
  value,
  actions,
}: EditorProps): ReactElement => {
  const avatarElement = avatar !== undefined && (
    <Avatar>
      {typeof avatar === 'string' ? (
        <img src={avatar} alt="comment-avatar" />
      ) : (
        avatar
      )}
    </Avatar>
  );

  const actionsElement = (
    <EditorActionsWrapper>
      {submitting === true ? (
        <Icon icon="loading" spin size="medium" intent="primary" />
      ) : (
        <Button.Icon
          type="submit"
          intent="primary"
          onClick={onSubmit}
          size="large"
          icon="send"
          data-test-id="submit-comment-btn"
        />
      )}
      {actions !== undefined && actions}
    </EditorActionsWrapper>
  );
  return (
    <EditorContainer>
      {avatarElement}
      <EditorWrapper>
        <Input.TextArea onChange={onChange} value={value} autoResize />
        {actionsElement}
      </EditorWrapper>
    </EditorContainer>
  );
};

export default Editor;
