import React, { useCallback, useEffect, useRef } from "react";
import styles from "styles/app.module.scss";
import reportWhite from "../../assets/images/report_white.svg";
import closeWhite from "../../assets/images/close_white.svg";
import checkCircleWhite from "../../assets/images/check_circle_white.svg";

export type SnackbarLevel = "info" | "error";

interface SnackbarProps {
  isOpen: boolean;
  level: SnackbarLevel;
  message: string;
  duration?: number;
  onClose: () => void;
}

const Snackbar: React.FC<SnackbarProps> = (props) => {
  const { isOpen, level, message, duration, onClose } = props;

  const timer = useRef(0);
  const onTimeout = useCallback(() => {
    timer.current = window.setTimeout(() => onClose(), duration);
  }, [onClose, duration]);

  const onCloseSnackbar = useCallback(() => {
    clearTimeout(timer.current);
    onClose();
  }, [onClose]);

  useEffect(() => {
    if (duration !== 0) {
      onTimeout();
    }
    return () => {
      clearTimeout(timer.current);
    };
  }, [duration, onTimeout]);

  const isAlert = level === "error" ? styles.isAlert : "";
  const isShow = isOpen ? styles.isShow : "";

  return (
    <div className={`${styles.snackbar} ${isAlert} ${isShow}`}>
      {level === "error" ? (
        <img src={reportWhite} className={styles.snackbarIcon} alt="check" />
      ) : (
        <img
          src={checkCircleWhite}
          className={styles.snackbarIcon}
          alt="report"
        />
      )}
      <p className={styles.txNormal}>{message}</p>
      {level === "error" && (
        <button
          style={{ marginLeft: "auto" }}
          type="button"
          onClick={onCloseSnackbar}
        >
          <img
            src={closeWhite}
            className={styles.snackbarIconClose}
            alt="close"
          />
        </button>
      )}
    </div>
  );
};

Snackbar.defaultProps = {
  duration: 0,
};

export default Snackbar;
