import React from 'react'
import ShareButtons from './ShareButtons'
import ShareLinkButton from './ShareLinkButton'
import Timestamp from './Timestamp'
import RichText from '../RichText'
import Expander from '../Expander'
import classnames from 'classnames'
import Headshot from '../Headshot'
import Byline from '../Byline'
import RecommendedLivePost from '../content-tree/RecommendedLivePost'
import { StructuredTreeFragment } from '@financial-times/cp-content-pipeline-client'

/* eslint-disable @typescript-eslint/no-explicit-any */
//TODO: CI-1975 remove "any" types
// this has been ported from x-dash, and a lot of what is expected into these arguments will take a lot of digging
//TODO: this component isn't adequately 'dumb', split into presentational and logic components
type indicators = {
  isOpinion?: boolean
}

const TruncatedPost: React.FC<React.PropsWithChildren<{ id: string }>> = ({
  id,
  children,
}) => {
  return (
    <div
      data-trackable="truncated-post"
      data-trackable-context-post={id}
      data-trackable-category="live-blog"
      className="x-live-blog-post__body n-content-body article--body o3-type-body-content-base"
    >
      <Expander
        expandLabel="Expand post"
        collapseLabel="Collapse post"
        onlyMobile={true}
        id={`truncated-${id}`}
      >
        {children}
      </Expander>
    </div>
  )
}

const truncatedSelector = () => {
  const prefix = '.x-live-blog-post__body >'
  const selectors = [
    'p',
    'blockquote',
    'ul',
    '.o-table-container',
    '.n-content-recommended--single-story',
    "[data-layout-name='card']",
    '.n-content-big-number',
    'hr',
    '.n-content-tweet',
    "[data-layout-name='timeline']",
  ]
  return selectors.map((item) => `${prefix} ${item}`).join(',')
}

export type LiveBlogPostProps = {
  id: string
  postId: string // Remove once wordpress is no longer in use
  title: string
  content: string // Remove once wordpress is no longer in use
  bodyHTML: string //ElasticSearch
  body: any // cp-content-pipeline
  publishedTimestamp: string // Remove once wordpress is no longer in use
  publishedDate: string
  isPinned: boolean
  articleUrl: string
  showShareButtons: boolean
  showShareLinkButton: boolean
  byline: StructuredTreeFragment
  ad: unknown
  indicators?: indicators
  authors: Array<any>
}
const LiveBlogPost: React.FC<LiveBlogPostProps> = ({
  id,
  postId, // Remove once wordpress is no longer in use
  title,
  content, // Remove once wordpress is no longer in use
  bodyHTML, //ElasticSearch
  body, // cp-content-pipeline
  publishedTimestamp, // Remove once wordpress is no longer in use
  publishedDate,
  articleUrl,
  showShareButtons = false,
  showShareLinkButton = false,
  byline,
  ad,
  isPinned,
  indicators = {},
  authors,
}) => {
  let postBody
  if (body && 'structured' in body) {
    // Content comes from cp-content-pipeline-api
    postBody = (
      <TruncatedPost id={id}>
        <RichText
          structuredContent={body.structured}
          components={{
            recommended: RecommendedLivePost,
          }}
        />
      </TruncatedPost>
    )
  } else {
    // Content comes from next-es or wordpress
    postBody = (
      <div
        className="x-live-blog-post__body n-content-body article--body o3-editorial-typography-body"
        dangerouslySetInnerHTML={{ __html: bodyHTML || content }}
      />
    )
    // add pinned post old version when comming from next-es or wordpress
    postBody = isPinned ? (
      <div
        data-o-component="o-expander"
        className="o-expander"
        data-o-expander-shrink-to="1"
        data-o-expander-item-selector={truncatedSelector()}
        data-o-expander-collapsed-toggle-text={'Expand post'}
        data-o-expander-expanded-toggle-text={'Collapse post'}
      >
        <div className="o-expander__content">{postBody}</div>
        <a className="o-expander__toggle o-expander__text--custom">
          <span className="o-expander__visually-hidden o3-type-detail">
            &nbsp;
          </span>
        </a>
      </div>
    ) : (
      postBody
    )
  }

  const author = authors?.[0] ?? null

  return (
    <article
      className={classnames('x-live-blog-post', {
        'x-live-blog-post--opinion': indicators.isOpinion,
        'x-live-blog-post--pinned': isPinned,
      })}
      data-trackable={isPinned ? 'pinned-post' : 'live-post'}
      data-trackable-context-pinned={isPinned}
      data-trackable-context-opinion={indicators.isOpinion}
      id={`post-${id || postId}`}
      data-x-component="live-blog-post"
    >
      <div className="x-live-blog-post__standout">
        {!author?.headshot && (
          <span
            className={classnames({
              'x-live-blog-post__pin-icon': isPinned,
              'x-live-blog-post__opinion-icon':
                !isPinned && indicators.isOpinion,
            })}
          ></span>
        )}
        {author?.headshot && indicators.isOpinion && (
          <Headshot
            headshot={author?.headshot}
            prefLabel={author?.prefLabel}
            streamPage={author?.streamPage}
            className={'x-live-blog-post__opinion-headshot'}
          />
        )}
        <div className="x-live-blog-post__meta-container">
          <div className="x-live-blog-post__meta">
            {indicators.isOpinion ? (
              <span className="x-live-blog-post__label--opinion x-live-blog-post__label o3-type-label">
                Live Opinion
              </span>
            ) : isPinned ? (
              <span className="x-live-blog-post__label o3-type-label">
                Editor's pick
              </span>
            ) : (
              ''
            )}
            {!isPinned && (
              <span>
                <Timestamp
                  publishedTimestamp={publishedDate || publishedTimestamp}
                  textCase="sentence"
                />
              </span>
            )}
          </div>
          <div className="x-live-blog-post__byline">
            <Byline structuredContent={byline} showEditedBy={false} />
          </div>
        </div>
        {showShareLinkButton && (
          <ShareLinkButton postId={id || postId} articleUrl={articleUrl} />
        )}
      </div>

      {title && (
        <h2 className="x-live-blog-post__title o3-type-display-sm">{title}</h2>
      )}
      {postBody}
      <div className="x-live-blog-post__controls">
        {showShareButtons && (
          <ShareButtons
            postId={id || postId}
            articleUrl={articleUrl}
            title={title}
          />
        )}
      </div>
      {ad as any}
    </article>
  )
}

export { LiveBlogPost }
