import React, { forwardRef, useImperativeHandle, useState, useRef } from 'react';
import './NotificationPro.css';

const ICON = { success: '✓', error: '✕', warning: '!', info: 'i' };

const NotificationPro = forwardRef(function NotificationPro({ duration = 4500 }, ref) {
  const [list, setList] = useState([]);
  const idRef = useRef(0);

  function close(id) { setList(l => l.filter(m => m.id !== id)); }
  function open(opts) {
    const id = ++idRef.current;
    setList(l => [...l, { id, type: opts.type || 'info', title: opts.title, desc: opts.desc }]);
    const d = opts.duration == null ? duration : opts.duration;
    if (d > 0) setTimeout(() => close(id), d);
    return id;
  }

  useImperativeHandle(ref, () => ({
    open,
    close,
    success: (t, d, dur) => open({ type: 'success', title: t, desc: d, duration: dur }),
    error: (t, d, dur) => open({ type: 'error', title: t, desc: d, duration: dur }),
    warning: (t, d, dur) => open({ type: 'warning', title: t, desc: d, duration: dur }),
    info: (t, d, dur) => open({ type: 'info', title: t, desc: d, duration: dur })
  }));

  return (
    <div className="kole-notification-wrap">
      {list.map(m => (
        <div key={m.id} className={`kole-notification is-${m.type}`}>
          <span className="kole-notification-icon">{ICON[m.type] || 'i'}</span>
          <div className="kole-notification-body">
            <div className="kole-notification-title">{m.title}</div>
            {m.desc ? <div className="kole-notification-desc">{m.desc}</div> : null}
          </div>
          <span className="kole-notification-close" onClick={() => close(m.id)}>✕</span>
        </div>
      ))}
    </div>
  );
});

export default NotificationPro;
