
import React from 'react';
import { InjectedIntlProps, injectIntl } from 'react-intl';
import ListItem from '@material-ui/core/ListItem';
import Typography from '@material-ui/core/Typography';
// import DeleteIcon from '@material-ui/icons/Delete';
import CircularProgress from '@material-ui/core/CircularProgress';
import moment from 'moment';
import { compose } from 'redux';
import { connect } from 'react-redux';
import messages from 'CommentSection/messages';
import {
  IComment,
} from 'CommentSection/types';
import ListItemText from '@material-ui/core/ListItemText';
import Button from '@material-ui/core/Button';
import { AstraTheme } from 'Themes/themes';
import {
  deleteCommentBeginAction, setReplyUser,
} from 'CommentSection/actions';
import ReactMarkdown from 'react-markdown';
import Linkify from 'react-linkify';
import { commentToolButtonStyle } from 'CommentSection/components/styles';
import 'CommentSection/components/reactMarkdownOverride.css';

export interface ICommentItemProps {
  comment: IComment;
  divider: boolean;
  key: string;
}
export interface IDispatchProps {
  deleteComment(comment: IComment): void;
  replyComment(userString: string): void;
}

const momentLocale = moment.locale();
moment.updateLocale(momentLocale, {
  calendar: {
    lastWeek: 'l, LT',
    sameElse: 'l, LT',
  },
});

const prettyCommentStyle = {
  fontFamily: AstraTheme.typography.fontFamily,
};

export const OwnerTools = ({ handleOnDelete, intl }) => {

  return (
    <div style={{ display: 'flex' }}>
      <Button
        id="comment_delete_button"
        style={commentToolButtonStyle}
        onClick={handleOnDelete}
        aria-label={intl.formatMessage(messages.deleteButton)}
      >
        <Typography
          color={'textSecondary'}
          style={{ fontSize: 'inherit', lineHeight: 1 }}
        >
          {intl.formatMessage(messages.deleteButton)}
        </Typography>
      </Button>
    </div>
  );
};
export const NonOwnerTools = ({ handleOnReply, intl }) => {

  return (
    <div style={{ display: 'flex' }}>
      <Button
        id="comment_reply_button"
        style={commentToolButtonStyle}
        onClick={handleOnReply}
        aria-label={intl.formatMessage(messages.replyButton)}
      >
        <Typography
          color={'textSecondary'}
          style={{ fontSize: 'inherit', lineHeight: 1 }}
        >
          {intl.formatMessage(messages.replyButton)}
        </Typography>
      </Button>
    </div>
  );
};

export const DeletedView = ({ undoDelete, wasDeleted, intl }) => {
  return (
    <div>
      <Typography>{intl.formatMessage(messages.undoWarning)}</Typography>
      <div style={{ display: 'flex' }}>
        <CircularCountdown/>
        <Button
          id="comment_reply_button"
          onClick={undoDelete}
          disabled={wasDeleted}
          aria-label={intl.formatMessage(messages.undoDeleteButton)}
        >
          {intl.formatMessage(messages.undoDeleteButton)}
        </Button>
      </div>
    </div>
  );
};
export const CircularCountdown = () => {
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    function tick() {
      setProgress(oldProgress => (oldProgress >= 100 ? oldProgress : oldProgress + 1));
    }

    const timer = setInterval(tick, 20);
    return () => {
      clearInterval(timer);
    };
  });

  return (
    <CircularProgress variant="determinate" value={progress} />
  );
};

let timer;
export class CommentItem extends
  React.Component<ICommentItemProps & InjectedIntlProps & IDispatchProps> {
  initialComment:IComment = {
    id: '',
    author: '',
    authorId: '',
    message: '',
    createdDate: '',
    isOwner: true,
  };
  state = { toBeDeleted: false, wasDeleted: false, toBeDeletedComment: this.initialComment };

  componentWillUpdate = (prevProps) => {
    if (prevProps.comment.id !== this.props.comment.id) {
      this.setState({ toBeDeleted: false, wasDeleted: false });
    }
  }
  onDelete = () => {
    // we want to make sure we delete the right one, even if props update
    this.setState({ toBeDeleted: true, toBeDeletedComment: this.props.comment });
    timer = setTimeout(
      () => {
        this.setState({ wasDeleted: true });
        this.props.deleteComment(this.state.toBeDeletedComment);
      },
      3500,
    );
  }
  undoDelete = () => {
    clearTimeout(timer);
    this.setState({ toBeDeleted: false });
  }

  onReply = () => {
    this.props.replyComment(`@[${this.props.comment.author}](${this.props.comment.authorId})`);
  }

  public render() {
    const {
      comment,
      divider,
      key,
    } = this.props;

    const prettyComment = comment.message.replace(/\@\[(.*?)\]\((.*?)\)/g, '**$1**');

    return (
      <ListItem
        key={key}
        divider={divider} // no divider at bottom
      >
        <ListItemText>
          {this.state.toBeDeleted && (
            <DeletedView
              undoDelete={this.undoDelete}
              wasDeleted={this.state.wasDeleted}
              intl={this.props.intl}
            />
          )}
          {!this.state.toBeDeleted && (
            <div>
              <div style={{ display: 'flex' }}>
                <Typography color="inherit" style={{ fontWeight: 'bold' }} >
                  {comment.author}
                </Typography>
                <Typography color="textSecondary" style={{ paddingLeft: 10 }}>
                  {moment(comment.createdDate).calendar()}
                </Typography>
              </div>
              <div style={prettyCommentStyle}>
                <Linkify>
                  <ReactMarkdown
                    source={prettyComment}
                    skipHtml={true}
                  />
                </Linkify>
              </div>
              {comment.isOwner && (
                <OwnerTools
                  handleOnDelete={this.onDelete}
                  intl={this.props.intl}
                />
              )}
              {!comment.isOwner && (
                <NonOwnerTools
                  handleOnReply={this.onReply}
                  intl={this.props.intl}
                />
              )}
            </div>
          )}
        </ListItemText>
      </ListItem>
    );
  }
}

export const mapDispatchToProps = (dispatch) => {
  return {
    deleteComment: (comment) => {
      console.log(comment);
      dispatch(deleteCommentBeginAction(comment));
    },
    replyComment: userString => dispatch(setReplyUser(userString)),
  };
};

const withConnect = connect(
  null,
  mapDispatchToProps,
);

export const CommentItemWithIntl = injectIntl(CommentItem, { withRef: true });

export default compose(
  withConnect,
)(CommentItemWithIntl);
