import * as React from "react"
import styled, { css } from "styled-components"
import { getConfig } from "jamplay-common/remote-config"
import withTranslate from "jamplay-common/i18n/withTranslate"
import { Header, HeaderSize } from "../Header"
import SocialPanel from "../SocialPanel"
import { Primary as PrimaryButton, Border as BorderedButton } from "../Button"
import gql from "graphql-tag"
import { Link } from "jamplay-common/routing"
import { getCategory } from "jamplay-common/enum/book-categories"
import { SocialMediaShareContentType } from "jamplay-common/client/share"
import { LoginDialog } from "../Dialog/LoginDialog"
import { withState } from "recompose"
type ActionPanelPropTypes = {
  book?: BookItemData

  loading?: boolean

  onFollowBookClick?: (bookId: string, isUnFollow?: boolean) => void

  setIsShowLoginDialog?: (v: boolean) => boolean
  isShowLoginDialog?: boolean
  user?: { _id: string }
}

const IconWithNumberLabelStyleContainer = styled.div.attrs({
  className: "IconWithNumberLabel"
})`
  display: flex;
  align-items: center;
  margin: 0 13px;

  .IconWithNumberLabel__icon {
    width: 30px;
    height: 30px;
    background-size: contain;
    background-position: center center;
    background-repeat: no-repeat;
    margin-right: 8px;
  }

  .IconWithNumberLabel__meta {
  }
  .IconWithNumberLabel__meta__value {
    font-weight: bold;
    line-height: 1em;
  }

  .IconWithNumberLabel__meta__label {
    font-size: 0.8em;
    color: ${(props) => props.theme.grey};
  }
  @media screen and (max-width: 325px) {
    flex-wrap: wrap;
  }
`
export const IconWithNumberLabel: React.SFC<{
  iconName: string
  value: string
  label: string
}> = (props) => {
  return (
    <IconWithNumberLabelStyleContainer>
      <div
        className="IconWithNumberLabel__icon"
        style={{
          backgroundImage: `url(${
            getConfig().publicRuntimeConfig.staticFolder
          }/ui-assets/images/${props.iconName}.png)`
        }}
      />
      <div className="IconWithNumberLabel__meta">
        <Header size={HeaderSize.three} className="heavent IconWithNumberLabel__meta__value">
          {props.value}
        </Header>
        <div className="heavent IconWithNumberLabel__meta__label">
          {props.label}
        </div>
      </div>
    </IconWithNumberLabelStyleContainer>
  )
}

type ActionPanelComponent = React.SFC<ActionPanelPropTypes> & {
  fragments?: { book: any }
}

const ActionPanelMobileStyle = css`
  flex-direction: column;
  align-items: center;
  .ActionPanel__info-wrapper {
    padding: 8px 0;
    width: 100vw;
    margin-bottom: 8px;
    border-bottom: 1px solid ${(props) => props.theme.borderGrey};
    justify-content: center;
  }
  .IconWithNumberLabel {
  }

  .ActionPanel__user-action-button-container {
    margin-top: 21px;
    width: 100%;
    box-sizing: border-box;
    justify-content: center;
  }
`
const ActionPanelTabletStyle = css`
  flex-direction: row;
  &:nth-child(1) {
    border-bottom: none;
  }
  .IconWithNumberLabel {
    &:nth-last-child(1) {
      margin-right: 26px;
      padding-right: 26px;
      border-right: 2px solid ${(props) => props.theme.borderGrey};
    }
  }
`
const ActionPanelStyleContainer = styled.div`
  display: flex;
  align-items: center;
  padding: 8px 0;
  margin-bottom: 8px;

  .ActionPanel__info-wrapper {
    display: flex;
    flex: 0 0 auto;
  }
  .SocialPanel {
    flex: 0 0 auto;
  }

  .ActionPanel__user-action-button-container {
    flex: 1 1 auto;
    padding: 0 8px;
    display: flex;
    justify-content: flex-end;
    .ActionPanel__user-action-button-container-wrapper {
      max-width: 480px;
      display: flex;
      flex-wrap: wrap;
      flex: 1 1 auto;
      a {
        margin: 0px 4px;
        &:nth-child(1) {
          margin-left: 0px;
        }
        &:nth-last-child(1) {
          margin-right: 0px;
        }
      }

      .ActionPanel__read-button-wrapper {
        flex: 3 1 auto;
        .ActionPanel__read-button {
          width: 100%;
        }
      }
      .ActionPanel__read-button,
      .ActionPanel__edit-button {
        flex: 3 1 auto;
      }

      .ActionPanel__edit-button {
        background-color: ${(props) => props.theme.gold};
        border-color: ${(props) => props.theme.gold};
      }

      .ActionPanel__follow-button {
        flex: 1 1 auto;

        &.followed {
          background-color: ${(props) => props.theme.mint};
          border-color: ${(props) => props.theme.mint};
        }
      }
    }
  }

  @media screen and (max-width: 900px) {
    ${ActionPanelMobileStyle};
    flex-direction: column;
  }
  @media screen and (min-width: 900px) {
    ${ActionPanelTabletStyle};
  }
`

const ActionPanelComponent: ActionPanelComponent = (
  props: ActionPanelPropTypes & withTranslatePropType
) => {
  if (!props.book) {
    return <div />
  }
  let { t } = props
  const {
    onFollowBookClick,
    isShowLoginDialog,
    user,
    setIsShowLoginDialog
  } = props

  const {
    commentCount,
    viewCount,
    episodeCount,
    recentRead,
    isOwner,
    _id,
    categories,
    firstEpisode,
    isInWishList
  } = props.book

  /**
   * If on loading every value will show as
   * " - "
   */
  let view = "-"
  let episode = "-"
  let comment = "-"

  if (typeof viewCount === "number") {
    view = viewCount.toLocaleString()
  }
  if (typeof episodeCount === "number") {
    episode = episodeCount.toLocaleString()
  }

  if (typeof commentCount === "number") {
    comment = commentCount.toLocaleString()
  }

  if (!t) {
    t = (s) => s
  }

  if (!firstEpisode) {
    return <div data-message="first-episode-not-found" />
  }

  if (!onFollowBookClick) {
    return <div>{"action-panel require onFollowBookClick"}</div>
  }

  const onFollowBook = () => {
    if (!user) {
      if (typeof setIsShowLoginDialog === "function") {
        setIsShowLoginDialog(true)
      }
    } else {
      onFollowBookClick(_id)
    }
  }
  const onUnFollowBook = () => onFollowBookClick(_id, true)

  const closeDialog = () => setIsShowLoginDialog && setIsShowLoginDialog(false)

  return (
    <ActionPanelStyleContainer>
      <div className="ActionPanel__info-wrapper">
        <IconWithNumberLabel
          iconName="view"
          label={t("views")}
          value={`${view}`}
        />
        <IconWithNumberLabel
          iconName="episode"
          label={t("episodes")}
          value={`${episode}`}
        />
        <IconWithNumberLabel
          iconName="comment"
          label={t("comment")}
          value={`${comment}`}
        />
      </div>
      <SocialPanel
        contentId={_id}
        contentType={SocialMediaShareContentType.BOOK}
        shareURL={Link.BookDetail.toPath({
          _id,
          category: categories && categories[0] && getCategory(categories[0]).prefix
        })}
      />
      <div className="ActionPanel__user-action-button-container">
        <div className="ActionPanel__user-action-button-container-wrapper">
          <Link.ReadEpisode
            params={{
              episodeId:
                (recentRead && recentRead.episodeId) || (firstEpisode[0] && firstEpisode[0]._id),
              category:
                categories && categories[0] ? getCategory(categories[0]).prefix
                : "all" ,
              bookId: _id
            }}
          >
            <a className="ActionPanel__read-button-wrapper">
              <PrimaryButton
                className="ActionPanel__read-button"
                children={!recentRead ? t("begin-read") : t("continue-read")}
              />
            </a>
          </Link.ReadEpisode>

          {!isOwner ? (
            !isInWishList ? (
              <BorderedButton
                onClick={onFollowBook}
                className="ActionPanel__follow-button"
                children={t("follow-book")}
              />
            ) : (
              <PrimaryButton
                onClick={onUnFollowBook}
                className="ActionPanel__follow-button followed"
                children={t("already-follow-book")}
              />
            )
          ) : null}

          {isOwner ? (
            <Link.EditBook params={{ bookId: _id }}>
              <a>
                <PrimaryButton
                  className="ActionPanel__edit-button"
                  children={t("edit-book")}
                />
              </a>
            </Link.EditBook>
          ) : null}
        </div>
      </div>
      {isShowLoginDialog ? <LoginDialog text={t("book/unable-to-follow-label-login")} onClose={closeDialog} /> : null}
    </ActionPanelStyleContainer>
  )
}

ActionPanelComponent.displayName = "ActionPanel"
ActionPanelComponent.defaultProps = {
  book: {
    _id: "NO_CONTENT",
    categories: []
  },
  loading: false
}

ActionPanelComponent.fragments = {
  book: gql`
    ## Action bar fragment
    fragment BookDetail__Action__Bookdata on Book {
      viewCount
      episodeCount
      commentCount

      isInWishList
      isOwner

      firstEpisode: episodes(sort: CREATED_AT_ASC, limit: 1) {
        _id
        title
      }
      recentRead {
        _id
        updatedAt
        episodeId
      }
    }
  `
}
const panelWithState = Object.assign(
  withState("isShowLoginDialog", "setIsShowLoginDialog", false)(
    ActionPanelComponent
  ),
  ActionPanelComponent
)
export default withTranslate(panelWithState) as ActionPanelComponent
