import isNil from 'lodash-es/isNil';

export const SUMMARY_PREVIEW_MAX_LENGTH = 290;

type SummaryView = {
  showEditor: boolean;
  showReadOnly: boolean;
  showEditButton: boolean;
  shouldRenderCard: boolean;
};

type SummaryViewParams = {
  withSummary: boolean;
  isCurrentUserReviewSubject: boolean;
  isReviewShared: boolean;
  summary: string | undefined;
  hasSummary: boolean;
  isEditing: boolean;
  hasSaveSummaryAction: boolean;
};

export const getPlainTextFromHtml = (value?: string) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(value || '', 'text/html');
  return doc.body.textContent || '';
};

export const getSummaryPreviewText = ({
  text,
  showMore,
}: {
  text: string;
  showMore: boolean;
}) => (showMore ? text : text.slice(0, SUMMARY_PREVIEW_MAX_LENGTH));

export const getSummaryView = ({
  withSummary,
  isCurrentUserReviewSubject,
  isReviewShared,
  summary,
  hasSummary,
  isEditing,
  hasSaveSummaryAction,
}: SummaryViewParams): SummaryView => {
  const canEdit =
    withSummary &&
    !isCurrentUserReviewSubject &&
    !isReviewShared &&
    (isNil(summary) || hasSaveSummaryAction);
  const showEditor = canEdit && (isEditing || !hasSummary);
  const showReadOnly = hasSummary && !showEditor;
  const showEditButton = canEdit && hasSummary && hasSaveSummaryAction;
  const shouldRenderCard = withSummary && (showReadOnly || showEditor);

  return {
    showEditor,
    showReadOnly,
    showEditButton,
    shouldRenderCard,
  };
};
