import { useCallback } from 'react';
import PropTypes from 'prop-types';
import { 
  Container,
  Row
} from 'react-bootstrap';
import moment from 'moment';
import { toast } from 'react-toastify';

// components

import ConfigurableIcon from '../common/display/ConfigurableIcon';

// functions

import apiLoader from '../../services/utilities/apiLoader';

// constants

const errorNumber = 656;

export default function ShowNotices({ 
  announcements,
  handleError,
  refreshAnnouncements,
  userId,
}) {

  const dismissAnnouncement = useCallback(

    async (announcementId) => {

      const context = 'ShowNotices.dismissAnnouncement';

      if (!announcementId) return;

      try {

        const { data } = await apiLoader({
          api: 'utilities/announcements/clear',
          global: true, // Use the Simplexable API to get the announcements.
          handleError,
          payload: { 
            announcementId,
            masterKey: process.env.REACT_APP_SIMPLEXABLE_API_TOKEN,
            userId 
          },
        });

        const {
          failure = 'no failure message was returned',
          success,
        } = data;

        if (!success) {

          handleError(new Error(`failure: ${failure}`), context, errorNumber);
          return;

        }

        refreshAnnouncements();
        toast.success('The announcement notice has been dismissed');

      } catch (e) {

        handleError(e, context, errorNumber);

      }

    }, 
    [
      handleError,
      refreshAnnouncements,
      userId,
    ]

  );

  if (!Array.isArray(announcements) || announcements.length === 0) return null;

  return (
    <Container className="mt-3 mb-3 border-gray-1">

      {announcements.map(({ 
        announcementContent, 
        announcementId, 
        created 
      }) => (

        <Row 
          className="size-80 alternate-1 p-3"
          key={announcementId}
        >

          <div className="size-80 text-muted mt-2 floats">

            <ConfigurableIcon 
              className="float-right"
              iconName="XCircle" 
              onClick={() => dismissAnnouncement(announcementId)}
              size={20}
              toolTipTitle="dismiss this notice"
            />

            <div className="float-left">
              Notice from Simplexable, {moment.unix(created).fromNow()}
            </div>

          </div>

          <div dangerouslySetInnerHTML={{ __html: announcementContent }} />

        </Row>

      ))}

    </Container>
  );
}

ShowNotices.propTypes = {
  announcements: PropTypes.arrayOf(
    PropTypes.shape({
      announcementId: PropTypes.string.isRequired,
      announcementContent: PropTypes.string.isRequired,
      created: PropTypes.number.isRequired
    })
  )
};