import { marked } from 'marked';

import styles from './Blockquote.module.css';

interface BlockquoteProps {
  quote: string;
  attribution?: string;
  source?: string;
  url?: string;
}

export default function Blockquote({
  quote,
  attribution,
  source,
  url,
}: BlockquoteProps) {
  const hasAttribution = !!attribution;
  const hasSource = !!source;
  const hasUrl = !!url;
  const showFooter = hasSource || hasAttribution;
  const attributionLinked = hasAttribution && hasUrl && !hasSource;
  const sourceLinked = hasSource && hasUrl;
  return (
    <blockquote className={styles.blockquote}>
      <div
        className={styles.quote}
        dangerouslySetInnerHTML={{ __html: marked.parse(quote) }}
      />
      {showFooter && (
        <footer className={styles.footer}>
          {hasAttribution && (
            <cite className={styles.attribution}>
              {attributionLinked ? (
                <a
                  href={url}
                  className={styles.link}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {attribution}
                </a>
              ) : (
                attribution
              )}
            </cite>
          )}
          {hasSource && (
            <cite className={styles.source}>
              {' '}
              –
              {sourceLinked ? (
                <a
                  href={url}
                  className={styles.link}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {source}
                </a>
              ) : (
                source
              )}
            </cite>
          )}
        </footer>
      )}
    </blockquote>
  );
}
