import clsx from "clsx";

import ArticleList from "@/components/article-list";
import CallToAction from "@/components/call-to-action";
import DatoContent from "@/components/content/dato";
import Image from "@/components/image";
import List from "@/components/list";
import { formatDate } from "@/helpers/date";
import { buildPageUrl } from "@/helpers/link";
import type { Post, StructuredContent } from "@/types";

import styles from "./styles.module.scss";

interface ArticleProps {
  article: Post;
}

export default function Article({ article }: ArticleProps) {
  const authors = new Intl.ListFormat("en").format(
    article?.author?.map((author) => author.name),
  );

  return (
    <article className={styles.article}>
      <header className={styles.head}>
        <div className={styles.coverImageContainer}>
          <Image
            className={styles.coverImage}
            image={article.coverImage}
            layout="intrinsic"
          />
        </div>
        <div className={styles.meta}>
          {article.author && article.author.length > 0 && (
            <p className={styles.author}>By {authors}</p>
          )}
          {article.date && (
            <p className={styles.date}>{formatDate(article.date)}</p>
          )}
        </div>
        <div className={styles.info}>
          <h1>{article.title}</h1>
          <p>{article.summary}</p>
        </div>
        <List
          className={styles.tags}
          items={article.tags.map((tag) => (
            <CallToAction
              key={tag.id}
              className={clsx(styles.tag, "tag")}
              href={buildPageUrl({
                type: "post",
                slug: `?tag=${tag.name.toLowerCase()}`,
              })}
            >
              {tag.name}
            </CallToAction>
          ))}
        />
      </header>
      <div className={styles.body}>
        <DatoContent structured={article.structuredText as StructuredContent} />
      </div>
      {!article.hideRelatedArticles && article.linkedPosts.length > 0 && (
        <div className={styles.footer}>
          <ArticleList
            title="Related articles"
            articles={article.linkedPosts}
          />
        </div>
      )}
    </article>
  );
}
