import React from 'react';
// import { InjectedIntlProps, injectIntl } from 'react-intl';
import { MentionsInput, Mention } from 'react-mentions';
import Button from '@material-ui/core/Button';
import Paper from '@material-ui/core/Paper';
import SendIcon from '@material-ui/icons/Send';
// import { connect } from 'react-redux';
// import injectReducer from 'utils/injectReducer';
// import reducer from 'CommentSection/reducer';
// import { compose } from 'redux';
// import commentSaga from 'CommentSection/sagas';
// import messages from 'CommentSection/messages';
// import {
//   makeSelectCourseInfo,
// } from 'ducks/RegMon/selectors';
// import {
//   createCommentBeginAction,
//   fetchUsersBeginAction,
//   setThreadIdBeginAction,
//   fetchCommentsBeginAction,
// } from 'CommentSection/actions';
import {
  // ContainerState,
  IComment,
  IUser,
  // RootState,
} from 'CommentSection/types';
// import {
//   makeSelectComments,
//   makeSelectUsers,
//   makeSelectReplyUser,
// } from 'CommentSection/selectors';
// import { CourseInfo } from 'ducks/RegMon/types';
// import injectSaga from 'utils/injectSaga';
// import { createStructuredSelector } from 'reselect';
import {
  mentionInputStyle,
  paperStyle,
  dividerStyle,
  commentStyling,
  buttonStyle,
} from 'CommentSection/components/styles';

export interface ICommentsSectionState {
  comments: IComment[];
  newNotificaitonValue: string;
  userSearch: boolean;
  users: any[];
  focused: boolean;
}

interface IDispatchProps {
  fetchComments(threadId): void;
  createComment(comment): void;
  fetchUsers(): void;
  setThreadId(threadId): void;
}

export interface IStateProps {
  comments: IComment[];
  users: IUser[];
  // courseInfo?: CourseInfo;
  threadId?: string;
  replyUser?: string;
}

export type AllProps = IStateProps & IDispatchProps;

export class CommentsSection
  extends React.Component<AllProps, ICommentsSectionState> {

  anchorEl:any = null;

  constructor(props) {
    super(props);

    const initialComments:IComment[] = [];
    const initialUsers:IUser[] = [];

    this.state = {
      comments: initialComments,
      newNotificaitonValue: '',
      userSearch: false,
      users: initialUsers,
      focused: false,
    };
  }

  componentDidMount = () => {
    this.setState({ comments: this.props.comments });
    this.props.fetchUsers();
  }

  componentDidUpdate = (prevProps) => {
    if (JSON.stringify(prevProps.comments) !== JSON.stringify(this.props.comments) ||
      prevProps.comments.length !== this.props.comments.length) {
    }
    if (prevProps.threadId !== this.props.threadId) {
      const threadId = this.props.threadId;
      this.props.fetchComments(threadId);
      this.props.setThreadId(threadId);
    }
    if (prevProps.users !== this.props.users) {
      const mappedUsers = this.props.users.map(u =>
      ({ id: u.id, display: `${u.firstName} ${u.lastName}` }));
      this.setState({ users: mappedUsers });
    }
    if (prevProps.replyUser !== this.props.replyUser) {
      const commentList = document.getElementById('comment_input');
      if (commentList) {
        commentList.focus();
      }
      const newCommentVal = `${this.props.replyUser} ${this.state.newNotificaitonValue}`;
      this.setState({ newNotificaitonValue: newCommentVal });
    }
  }

  updateComment = (e) => {
    if (e.target.value !== '\n') {
      this.setState({
        newNotificaitonValue: e.target.value,
      });
    }
  }

  checkEnter = (e) => {
    if (e.keyCode === 13 && !this.state.userSearch) {
      this.createComment();
    }
  }

  createComment = () => {
    const threadId = this.props.threadId;
    const threadName = this.props.threadId;
    const newComment = {
      comment_text: this.state.newNotificaitonValue,
      thread_id: threadId,
      source_url: window.location.pathname + window.location.search,
      thread_name: threadName,
    };
    this.props.createComment(newComment);
    this.setState({ newNotificaitonValue: '', userSearch: false });
  }

  getData = (query) => {
    let returnedUsers;
    // if state users is empty, either from filtering down or delayed sagas, grab users from props
    if (this.state.users === []) {
      const mappedUsers = this.props.users.map(u =>
        ({ id: u.id, display: `${u.firstName} ${u.lastName}` }));
      this.setState({ users: mappedUsers });
      returnedUsers = mappedUsers.filter(u =>
        (u.display.toLowerCase().includes(query.toLowerCase())));
    } else {
      returnedUsers = this.state.users.filter(u =>
        (u.display.toLowerCase().includes(query.toLowerCase())));
    }
    returnedUsers.sort((a, b) => {
      if (a.display < b.display) {
        return -1;
      }
      if (a.display > b.display) {
        return 1;
      }
      return 0;
    });
    // on long lists, truncate and give a sense of list size
    if (returnedUsers.length > 10) {
      const userCount = returnedUsers.length;
      returnedUsers = returnedUsers.slice(0, 10);
      returnedUsers.push({
        id: 'count',
        // display: `(${userCount} ${this.props.intl.formatMessage(messages.userListResultCount)})`,
        display: `(${userCount} results)`,
      });
    }
    // userSearch disappears when no users
    this.setState({ userSearch: (returnedUsers.length > 0) });
    return returnedUsers;
  }
  addUser = () => {
    this.setState({ userSearch: false });
  }

  public render() {

    // const intl = this.props.intl;
    // const message = messages.commentPlaceHolder;

    return (
      <div style={commentStyling} >
        <div style={dividerStyle} />
        <Paper
          style={paperStyle}
        >
          <div style={{ display: 'flex' }}>
            <div style={{ width: '100%' }}>
              <MentionsInput
                id="comment_input"
                value={this.state.newNotificaitonValue}
                onFocus={this.scrollDown}
                onBlur={this.handleBlur}
                onChange={this.updateComment}
                onKeyDown={this.checkEnter}
                allowSpaceInQuery={true}
                // aria-label={intl.formatMessage(message)}
                // placeholder={intl.formatMessage(message)}
                style={mentionInputStyle(this.state.focused)}
              >
                <Mention
                  trigger="@"
                  data={this.getData}
                  onAdd={this.addUser}
                  appendSpaceOnAdd={true}
                  style={mentionInputStyle(this.state.focused).mention}
                />
              </MentionsInput>
            </div>
            <Button
              id="comment_input_button"
              style={buttonStyle(this.state.focused)}
              onClick={this.createComment}
              // aria-label={intl.formatMessage(messages.sendButton)}
            >
              <SendIcon/>
            </Button>
          </div>
        </Paper>
      </div>
    );
  }

  scrollDown = () => {
    const commentList = document.getElementById('comment_list');
    if (commentList) {
      // we want smooth scroll but IE/Edge/Safari doesn't support it
      // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
      const isIE = navigator.userAgent.indexOf('MSIE') !== -1;
      const isEdge = navigator.userAgent.indexOf('Edge') !== -1;
      const isSafari = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1;
      if (isIE || isEdge || isSafari) {
        window.scrollTo(0, commentList.offsetTop - 250);
      } else {
        window.scrollTo({
          top: commentList.offsetTop - 250,
          behavior: 'smooth',
        });
      }
    }
    this.setState({ focused: true });
  }

  handleBlur = () => {
    this.setState({ focused: false });
  }
}

// export const mapStateToProps = createStructuredSelector<RootState, IStateProps>({
//   // comments: makeSelectComments(),
//   // users: makeSelectUsers(),
//   // courseInfo: makeSelectCourseInfo(),
//   // replyUser: makeSelectReplyUser(),
// });

// export const mapDispatchToProps = (dispatch) => {
//   return {
//     fetchComments: threadId => dispatch(fetchCommentsBeginAction(threadId)),
//     setThreadId: threadId => dispatch(setThreadIdBeginAction(threadId)),
//     fetchUsers: () => dispatch(fetchUsersBeginAction()),
//     createComment: comment => dispatch(createCommentBeginAction(comment)),
//   };
// };

// const withConnect = connect(
//   mapStateToProps,
//   mapDispatchToProps,
// );

// const withReducer = injectReducer<ContainerState>({ reducer, key: 'comments' });

// export const CommentsSectionWithIntl = injectIntl(CommentsSection, { withRef: true });
// const withSaga = injectSaga({ saga: commentSaga, key: 'comments' });

export default CommentsSection;

// export default compose(
//   withConnect,
//   withReducer,
//   // withSaga,
// )(CommentsSectionWithIntl);
