import React, { useEffect, useState, FC } from 'react';
import { NotificationProps } from './types';
import classnames from 'classnames';

const Notification: FC<NotificationProps> = ({
  type = 'info',
  title = null,
  message = null,
  timeOut = 5000,
  onClick = () => {},
  onRequestHide = () => {},
}) => {

  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (timeOut !== 0) {
      const timeoutId = setTimeout(() => {
        requestHide();
      }, timeOut);

      setTimer(timeoutId);

      return () => {
        if (timer) clearTimeout(timer);
      };
    }
  }, [timeOut]);

  const handleClick = () => {
    onClick();
    requestHide();
  };

  const requestHide = () => {
    onRequestHide();
  };

  const className = classnames(['notification-gtc-rc', `notification-gtc-rc-${type}`]);

  const renderTitle = title ? <h4 className="title">{title}</h4> : null;

  return (
    <div className={className} onClick={handleClick}>
      <div className="notification-gtc-rc-message" role="alert">
        {renderTitle}
        <div className="message">{message}</div>
      </div>
    </div>
  );
};

export default Notification;