/**
 * BookItem with synopsis
 * =====
 * mainly use in search result and
 * landing page category section
 */
import * as React from "react"
import styled from "styled-components"
import * as moment from "moment"
import CoverBaseElement from "../Book/components/BookThumbnail"
import { AuthorItemWithSubLabel } from "../Author"
import RatingStarIndicator from "./RatingStarIndicator"
import breakpoint from "styled-components-breakpoint"
import withTranslate from "jamplay-common/i18n/withTranslate"
import { BookTags } from "./components/BookTag"
import Analytic from "jamplay-common/client/analytic"

import getConfig from "jamplay-common/remote-config"
import { BookSynopsis } from "./components/BookSynopsis"
import { generateHighlightTextMarkup } from "../../utils/highlight-text"
import { Link } from "jamplay-common/routing"
import gql from "graphql-tag"
import { AnimatedBackground } from "../ContentPlaceholder"
import { getCategory } from "jamplay-common/enum/book-categories"

const BookItemContainer = styled.div.attrs({
  className: "BookItemContainer"
})`
  margin: 21px 0;
  a {
    color: #333;
  }
  &:first-child {
    margin-top: 0;
  }
  &:last-child {
    margin-bottom: 0;
  }
  .BookItem__header-title {
    position: relative;
    white-space: pre-wrap;
    cursor: pointer;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-height: normal;
    max-width: 100%;
    max-height: 3em;
    line-height: 1.5em;
    margin: 0 0px 0px 0;
    -webkit-box-orient: vertical;
    white-space: pre-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
    padding: 0px 0px;
  }

  .BookItem p {
    display: block;
    padding: 8px 0px;
    display: -webkit-box;
    font-family: -MN-Lanna;
    -webkit-line-clamp: 3;
    line-height: normal;
    margin: 5px 0;
    -webkit-box-orient: vertical;
    white-space: pre-wrap;
    overflow: hidden;
    text-overflow: ellipsis;
    overflow: hidden;
    line-height: 1.7rem;
    font-size: 1rem;
    max-height: 5.5rem;
  }

  .BookItem__inner-wrapper {
    display: flex;
  }

  .BookItem__cover-wrapper {

    ${breakpoint("mobile")`
      flex: 0 0 100px;
      width: 100px;
    `}

    ${breakpoint("tablet")`
      flex: 0 0 120px;
      width: 120px;
    `}

    ${breakpoint("desktop")`
      flex: 0 0 160px;
      width: 160px;
    `}
  }

  .BookItem__info-wrapper {
    flex: 1 1 auto;
    padding-left: 21px;
    display: flex;
    flex-direction: column;
  }
  .BookItem__episode-count {
    position: relative;
    align-self: flex-start;
    display: inline-block;
  }

  .BookItem__synopsis-wrap {
    position: relative;
    display: inline-block;
  }

  .BookItem__space {
    flex: 1 1 auto;
  }
  .BookItem__update-at-label-wrap {
    position: relative;
    align-self: flex-start;
    display: inline-block;
  }
  .BookItem__updated-at-label {
    color: ${(props: any) => props.theme.labelGrey};
    margin-bottom: 3px;
    padding-bottom: 0;
    font-size: 0.8em;
  }
  .BookItem__tags-wrapper {
    margin: 0px -3px;
  }
`

type BookItemWithDescriptionPropType = {
  t?: (s: string) => string
  book: BookItemData
  loading?: boolean
  highlightText?: string
}
type BookItemWithDescriptionComponent = React.SFC<
  BookItemWithDescriptionPropType
> & { fragments?: { book: any } }

export const BookItemWithDescription: BookItemWithDescriptionComponent = (
  props
) => {
  const {} = getConfig()

  const {
    title,
    publishedAt,
    synopsis,
    viewCount,
    author,
    _id,
    ratingSummary,
    episodeCount,
    categories
  } = props.book
  const { loading } = props
  function SendViewBookDetialByCoverEvent(ga) {
    return () => {
      ga.sendEvent("search_result", "view_book_detail_by_cover", `${title}`, 0)
    }
  }

  function SendViewBookDetailByTitleEvent(ga) {
    return () => {
      ga.sendEvent("search_result", "view_book_detail_by_title", `${title}`, 0)
    }
  }

  function SendClickOnTagEvent(ga) {
    return (item) => {
      ga.sendEvent("search_result", "click_on_tag", item, 0)
    }
  }

  if (!author) {
    return null
  }

  let t: (s) => string = props.t as any
  if (!t) {
    t = (s) => s
  }

  const category = getCategory(categories[0])

  return (
    <Analytic>
      {(ga) => (
        <BookItemContainer>
          <div className="BookItem__inner-wrapper">
            <div
              className="BookItem__cover-wrapper"
            >
              <Link.BookDetail
                key={_id}
                params={{ _id, category: category.prefix }}
                onClick={SendViewBookDetialByCoverEvent(ga)}
              >
                <a>
                  <CoverBaseElement loading={loading} book={props.book} />
                </a>
              </Link.BookDetail>
            </div>
            <div className="BookItem__info-wrapper">
              <h5 className="BookItem__header-title">
                {props.loading ? (
                  <AnimatedBackground style={{ paddingTop: 8 }} />
                ) : null}
                <span>
                  <Link.BookDetail
                    key={_id}
                    params={{ _id, category: category.prefix }}
                    onClick={SendViewBookDetailByTitleEvent(ga)}
                  >
                    <a>
                      <span
                        style={{opacity: loading ? 0 : 1}}
                        dangerouslySetInnerHTML={{
                          __html: `${generateHighlightTextMarkup(
                            title || "",
                            props.highlightText
                          )}`
                        }}
                      />
                    </a>
                  </Link.BookDetail>
                </span>
              </h5>
              <BookTags book={props.book} onClick={SendClickOnTagEvent(ga)} />
              {ratingSummary ? (
                <RatingStarIndicator
                  average={ratingSummary.average}
                  count={ratingSummary.count}
                />
              ) : null}

              <h6 className="BookItem__episode-count">
                {props.loading ? (
                  <AnimatedBackground style={{ paddingTop: 8 }} />
                ) : null}
                <span style={{opacity: props.loading ? 0 : 1}}>{`${episodeCount || 0} ${t("book/episodes")}`}</span>
              </h6>
              {
                <AuthorItemWithSubLabel
                  {...author}
                  loading={props.loading}
                  name={generateHighlightTextMarkup(
                    author ? author.name : "",
                    props.highlightText || ""
                  )}
                  subLabel={`${(viewCount && viewCount.toLocaleString()) ||
                    0} ${t("views")}`}
                />
              }

              <div className="BookItem__synopsis-wrap">
                {props.loading ? (
                  <AnimatedBackground style={{ paddingTop: 8 }} />
                ) : null}
                <BookSynopsis>{synopsis || ""}</BookSynopsis>
              </div>

              <div className="BookItem__space" />
              <div className="BookItem__update-at-label-wrap">
                {props.loading ? (
                  <AnimatedBackground style={{ paddingTop: 13 }} />
                ) : null}
                <p
                  className="BookItem__updated-at-label"
                  dangerouslySetInnerHTML={{
                    __html: `${t("book/published-at")} ${moment(
                      publishedAt
                    ).fromNow()}`
                  }}
                />
              </div>
            </div>
          </div>
        </BookItemContainer>
      )}
    </Analytic>
  )
}

BookItemWithDescription.displayName = "BookItemWithDescription"
BookItemWithDescription.defaultProps = {
  highlightText: "NOTHING_TO_HIGH_LIGHT_PLEASE_SKIP_THIS",
  book: {
    _id: "NO_ID",
    title: "NO_CONTENT",
    categories: ["NONE"],
    author: {
      name: "NO_CONTENT",
      _id: "NO_CONTENT",
      profilePicture: "NO_CONTENT"
    }
  }
}
BookItemWithDescription.fragments = {
  book: gql`
    fragment BookItemWithDescriptionData on Book {
      _id
      title
      thumbnailImage
      _id
      viewCount
      lastEpisodePublishedAt
      categories
      synopsis
      ratingSummary {
        count
        average
      }
      episodeCount
      publishedAt
      author {
        _id
        name
        profilePicture
      }
    }
  `
}

export default withTranslate(BookItemWithDescription) as React.SFC<{
  book?: BookItemData
  highlightText?: string
  loading?: boolean
}> & { fragments: any }
