import React from 'react'
import Byline from '../Byline'
import type { ArticleQuery } from '@financial-times/cp-content-pipeline-client'
import ftDateFormat from '@financial-times/ft-date-format'

type ArticleInfoProps = {
  content: ArticleQuery['content']
}

const ArticleInfo: React.FC<React.PropsWithChildren<ArticleInfoProps>> = ({
  children,
  content,
}) => {
  const isLiveBlogPackage = content.__typename === 'LiveBlogPackage'
  const formattedFirstPublishedDate = ftDateFormat.format(
    new Date(content.firstPublishedDate),
    'date'
  )
  const formattedPublishedDate = ftDateFormat.format(
    new Date(content.publishedTimestamp),
    'date'
  )

  const displayPublishedDate = content.publishedDate && !isLiveBlogPackage
  const displayUpdatedDate =
    new Date(content.firstPublishedDate).getTime() !==
    content.publishedTimestamp
  const isPublishedMoreThanOneDayAgo =
    Date.now() - new Date(content.firstPublishedDate).getTime() >
    24 * 60 * 60 * 1000

  return (
    <div className="article-info o3-editorial-typography-byline">
      <div className="article-info__time-byline-row">
        <div className="article-info__time-byline-content">
          {content.byline && content.__typename !== 'Audio' && (
            <Byline
              structuredContent={content.byline}
              showEditedBy={isLiveBlogPackage}
            />
          )}
        </div>
        {!displayPublishedDate && children}
      </div>
      {displayPublishedDate && (
        <div className="article-info__time-byline-row">
          <div className="article-info__time-byline-content">
            <p className="article-info__timestamp-item">
              Published
              <time
                data-o-component="o-date"
                {...(isPublishedMoreThanOneDayAgo
                  ? { 'data-o-date-format': 'MMM d yyyy' }
                  : {})}
                className="article-info__timestamp o3-editorial-typography-byline-timestamp o-date"
                dateTime={content.firstPublishedDate}
              >
                {formattedFirstPublishedDate}
              </time>
            </p>
            {displayUpdatedDate && (
              <p className="article-info__timestamp-item article-info__updated-timestamp">
                Updated
                <time
                  data-o-component="o-date"
                  data-o-date-format={
                    isPublishedMoreThanOneDayAgo ? 'MMM d yyyy, HH:mm' : 'HH:mm'
                  }
                  className="article-info__timestamp o3-editorial-typography-byline-timestamp o-date"
                  dateTime={content.publishedDate}
                >
                  {formattedPublishedDate}
                </time>
              </p>
            )}
          </div>
          {children}
        </div>
      )}
    </div>
  )
}

export default ArticleInfo
