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

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

const MessagePro = forwardRef(function MessagePro({ duration = 3000 }, 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', content: opts.content, closable: opts.closable }]);
    const d = opts.duration == null ? duration : opts.duration;
    if (d > 0) setTimeout(() => close(id), d);
    return id;
  }

  useImperativeHandle(ref, () => ({
    open,
    close,
    success: (c, d) => open({ type: 'success', content: c, duration: d }),
    error: (c, d) => open({ type: 'error', content: c, duration: d }),
    warning: (c, d) => open({ type: 'warning', content: c, duration: d }),
    info: (c, d) => open({ type: 'info', content: c, duration: d }),
    loading: (c, d) => open({ type: 'loading', content: c, duration: d })
  }));

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

export default MessagePro;
