import {
  OverlayTrigger,
  Tooltip
} from 'react-bootstrap';
import { Trash } from '@phosphor-icons/react';
import { replace } from 'lodash';
import apiLoader from '../../../services/utilities/apiLoader';
import useLoadingMessages from '../../hooks/useLoadingMessages';
const DOMPurify = require('dompurify')(window);

function ShowMessages({ 
  checkMessages,
  handleError,
  messageCount,
  messages,
  setLoadingMessages
}) {

  const nowRunning = 'utilities/messages/ShowMessages.jsx';
  const errorNumber = 352;

  const { 
    addLoadingMessage, 
    removeLoadingMessage 
  } = useLoadingMessages(setLoadingMessages);

  const onDelete = async (messageId) => {

    const context = `${nowRunning}.onDelete`;
    const loadingMessage = 'Deleting the message...';

    try {

      addLoadingMessage(loadingMessage);
      const api = 'utilities/utilities/messages/delete';
      const payload = { messageId };
      const { data } = await apiLoader({ api, payload });

      if (!data.success) {

        handleError(data.failure, context, errorNumber, true);
        return;

      }

      await checkMessages();

    } catch (e) {

      handleError(e, context, errorNumber);

    } finally {

      removeLoadingMessage(loadingMessage);

    }

  };

  try {

    if (messageCount < 1) return null;

    return (

      <>

        {messages.map((message, key) => {

          const { 
            content, 
            messageId, 
            sentTime, 
            userName 
          } = message;

          return (

            <div 
              className="message" 
              key={key}
            >

              <div dangerouslySetInnerHTML={{  __html: DOMPurify.sanitize(replace(content, /\n/g, '<br />'))}}></div>

              <div className="text-right size-80">

                from {userName}, sent {sentTime}

                <OverlayTrigger
                  delay={{ hide: 100, show: 200 }}
                  overlay={(props) => (
                    <Tooltip {...props}>delete message</Tooltip>
                  )}
                  placement="bottom"
                >
                  <span className="text-red" onClick={() => onDelete(messageId)}>
                    &nbsp;<Trash size={20} />
                  </span>
                </OverlayTrigger>

              </div>

            </div>

          );

        })}
        
      </>

    );
    
  } catch (e) {

    handleError(e, nowRunning, errorNumber);
    return null;

  }

}

export default ShowMessages;