import React, { PropsWithChildren } from 'react'
import { StructuredTreeFragment } from '@financial-times/cp-content-pipeline-client'

import RichText from '../RichText'
import { ContentProps } from '../types'
import * as ComponentWorkarounds from '../content-tree/Workarounds'

type BylineProps = {
  showEditedBy: boolean
  structuredContent: StructuredTreeFragment
}

interface AuthorLinkProps extends ContentProps<ComponentWorkarounds.Author> {}

const AuthorLink: React.FC<PropsWithChildren<AuthorLinkProps>> = (props) =>
  props.content.concept ? (
    <a
      className="o3-editorial-typography-byline-author"
      href={props.content.concept.relativeUrl}
      data-trackable="author"
    >
      {props.children}
    </a>
  ) : null

const bylineComponents = {
  author: AuthorLink,
}

const Byline: React.FC<BylineProps> = ({ structuredContent, showEditedBy }) => {
  return (
    <p className="article-info__byline o3-editorial-typography-byline">
      {showEditedBy && (
        <span>
          Edited by <br />
        </span>
      )}
      {typeof structuredContent === 'string' ? (
        <>{structuredContent}</>
      ) : (
        <RichText
          structuredContent={structuredContent}
          components={bylineComponents}
        />
      )}
    </p>
  )
}

export default Byline
