import Toast from "backpack-ui/dist/components/toast";
import * as React from "react";

const { Component } = React;

export type ToastType = "error" | "info" | "success" | "warning";

export interface IToastProps {
  message?: string;
  url?: string;
  buttonLabel?: string;
  type?: ToastType;
  duration?: number;
  animationDuration?: number;
  visible?: boolean;
  title?: string;
  onClose?: () => void;
  direction?: "bottom" | "top";
  affixed?: boolean;
}

export interface IToastState {
  hasAnimated: boolean;
  isVisible: boolean;
}

export default class GlobalToast extends React.Component<IToastProps, IToastState> {
  public props: IToastProps;
  public state: IToastState;

  constructor(props) {
    super(props);

    this.state = {
      hasAnimated: props.visible,
      isVisible: props.visible,
    };

    this.open = this.open.bind(this);
    this.close = this.close.bind(this);
    this.triggerAnimation = this.triggerAnimation.bind(this);
  }

  public componentDidMount() {
    const { message, type } = this.props;

    if (message && type) {
      this.triggerAnimation();
    }
  }

  public triggerAnimation() {
    this.open();

    setTimeout(() => {
      this.close();
    }, this.props.duration);
  }

  public componentWillReceiveProps(nextProps) {
    if (nextProps.visible !== this.props.visible) {
      if (nextProps.visible) {
        this.triggerAnimation();
      }
    }
  }

  public open() {
    const { animationDuration } = this.props;

    this.setState({
      isVisible: true,
    });

    setTimeout(() => {
      this.setState({
        hasAnimated: true,
      });
    }, animationDuration);
  }

  public close() {
    const {
      onClose,
      animationDuration,
    } = this.props;

    this.setState({
      hasAnimated: false,
    });

    setTimeout(() => {
      this.setState({
        isVisible: false,
      });

      if (onClose && (typeof onClose === "function")) {
        onClose();
      }
    }, animationDuration);
  }

  public render() {
    const { message, title, type, buttonLabel, url } = this.props;

    return (
      <Toast
        visible={this.state.hasAnimated}
        onClose={this.close}
        direction="bottom"
        title={title}
        buttonLabel={buttonLabel}
        url={url}
        type={type}
        affixed
      >
        {message}
      </Toast>
    );
  }
}
