import React from 'react';
import { DocumentWithCategory } from '../store/documents.types';
import { AnyAction } from 'redux';
import * as Text from 'app/shared/components/text/text';
import { getFileIcon } from 'app/shared/components/FileType/fileTypeIconHelper';
import cx from 'classnames';
import { useSelector } from 'react-redux';
import { selectDocumentBookmarksLoadingStatus } from '../store/documents.selectors';

export interface Props {
  document: DocumentWithCategory;
  getDocumentFile: (documentId: number) => AnyAction;
  isBookmarked: boolean;
  onBookmarkRemove: (documentId: number) => AnyAction;
  onBookmarkAdd: (documentId: number) => AnyAction;
}

const DocumentsListItem = ({
  document,
  getDocumentFile,
  isBookmarked,
  onBookmarkAdd,
  onBookmarkRemove,
}: Props) => {
  const isAwaitingBookmarkToggle = useSelector(selectDocumentBookmarksLoadingStatus);

  const handleDownload = (event) => {
    event.preventDefault();
    getDocumentFile(document.id);
  };

  const handleBookmarkToggle = () => {
    if (!isAwaitingBookmarkToggle) {
      if (isBookmarked) {
        onBookmarkRemove(document.id);
      } else {
        onBookmarkAdd(document.id);
      }
    }
  };

  const bookmarkClassName = cx('u-font-size--big-icon', 'u-cursor--pointer',
    { 'icon-bookmark': !isBookmarked },
    { 'icon-bookmark-marked': isBookmarked },
  );

  return <div className="c-documents-list-item o-layout o-layout--space-between o-gutter--medium u-flex-column u-flex-lg-row">
    <div className="o-layout o-gutter-lg-right u-flex-column u-flex-lg-row">
      <div className="c-documents-list-item__icon-wrapper o-layout o-layout--aligned o-layout--justified u-margin-bottom u-margin-lg-bottom--none">
        <div className="c-documents-list-item__icon">
          {getFileIcon(document.fileType)}
        </div>
      </div>
      <div className="u-margin-lg-left u-margin-bottom--medium u-margin-lg-bottom--none">
        <Text.Menu extraClass="u-color--dark-grey u-margin-bottom--small">
          {`${document.date} | ${document.category}`}
        </Text.Menu>
        <Text.Paragraph extraClass="u-margin-bottom--tiny">{document.name}</Text.Paragraph>
        {document.description !== null &&
          <div className="c-documents-list-item__description" dangerouslySetInnerHTML={{ __html: document.description }} />
        }
      </div>
    </div>
    <hr className="c-documents-list-item__separator"/>
    <div className="o-layout o-layout--aligned u-margin-top u-margin-lg-top--none u-justify-content-end u-justify-content-initial u-margin-right">
      <i
        className="icon-download-2 u-font-size--big-icon u-margin-right--jumbo u-margin-md-right--big u-cursor--pointer"
        onClick={handleDownload}
      />
      <i className={bookmarkClassName} onClick={handleBookmarkToggle} />
    </div>
  </div>;
};

export default DocumentsListItem;
