import * as React from "react"
import withTranslate from "jamplay-common/i18n/withTranslate"
import styled from "styled-components"
import * as Button from "../Button"
import { graphql, compose } from "react-apollo"
import gql from "graphql-tag"
import { getConfig } from "jamplay-common/remote-config"
import { generateHighlightTextMarkup } from "../../utils"
import { AvatarThumbnail } from "./components/AuthorThumbnail"
import Analytic from "jamplay-common/client/analytic"
import { dataIdFromObject } from "jamplay-common/client/provider"
export function getApolloId(__typename, id) {
  return dataIdFromObject({ __typename, _id: id })
}
const AuthorItemContainer = styled.div.attrs({
  className: "AuthorItem"
})`
  .AvatarThumnail {
    width: 80px;
    height: 80px;
    border: 1px solid ${(props) => props.theme.borderGrey};
  }
  display: flex;
  .AuthorItem__info-container {
    display: flex;
    width: 90%;
    min-width: 110px;
  }
  .AuthorItem__info-wrap {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90%;
    margin-left: 18px;
    margin-right: 18px;
    color: ${(props) => props.theme.matteBlack};
  }
  a {
    color: ${(props) => props.theme.matteBlack};
  }

  h5 {
    overflow: hidden;
    text-overflow: ellipsis;
  }
  margin: 21px 0;
  border-bottom: 1px solid ${(props) => props.theme.borderGrey};
  padding-bottom: 20px;

  .follow-button {
    padding: 6px 12px;
    color: ${(props) => props.theme.white};
    border-bottom: 1px solid ${(props) => props.theme.labelGrey};
    font-size: 1rem;
    font-weight: 600;
  }

  .unfollow-button {
    font-size: 1rem;
    font-weight: 600;
  }
`

const { publicRuntimeConfig } = getConfig()

interface IAuthorItemSubscribePropTypes extends withTranslatePropType {
  highlightText: string
  authorId: string
  author: AuthorItemData
  requestFollow?: any
  requestUnFollow?: any
  subscriptStatus?: boolean
  refetch?: any
}

@(graphql as any)(
  gql`
    {
      user {
        _id
      }
    }
  `,
  {
    props: ({ data }) => ({ user: data.user }),
    options: {
      context: {
        service: "nap"
      }
    }
  }
)
@withTranslate
class AuthorItemSubscribe extends React.Component<
  IAuthorItemSubscribePropTypes & { url?: any; user?: any }
> {
  constructor(props) {
    super(props)
  }
  public onclickRequestFollow = () => {
    if (!this.props.user) {
      window.location.href = `/login?asPath=${window.location.href}`
    } else {
      this.props.requestFollow(this.props.authorId).then((res) => {
        this.props.refetch()
      })
    }
  }
  // requestUnFollow
  public onclickRequestUnFollow = () => {
    if (!this.props.user) {
      window.location.href = `/login?asPath=${window.location.href}`
    } else {
      this.props.requestUnFollow(this.props.authorId).then((res) => {
        this.props.refetch()
      })
    }
  }

  public sendviewAuthorDetailByImageEvent(ga) {
    return () =>
      ga.sendEvent(
        "search_result",
        "view_author_detail_by_image",
        `${this.props.author.name}`,
        0
      )
  }

  public sendViewAuthorDetailByNameEvent(ga) {
    return () => () =>
      ga.sendEvent(
        "search_result",
        "view_author_detail_by_name",
        `${this.props.author.name}`,
        0
      )
  }
  public render() {
    let { t } = this.props as any
    if (!t) {
      t = (s) => s
    }
    return (
      <Analytic>
        {(ga) => (
          <AuthorItemContainer>
            <a
              href={`/author/${this.props.author._id}`}
              onClick={this.sendviewAuthorDetailByImageEvent(ga)}
            >
              <AvatarThumbnail
                style={{
                  backgroundImage: this.props.author.profilePicture
                    ? `url( ${this.props.author.profilePicture} )`
                    : `url(${publicRuntimeConfig.staticFolder ||
                        ""}/ui-assets/images/profile-picture/default-pic-editor.jpg)`
                }}
              />
            </a>
            <div className="AuthorItem__info-wrap heavent">
              <a
                href={`/author/${this.props.author._id}`}
                onClick={this.sendViewAuthorDetailByNameEvent(ga)}
              >
                <h5
                  dangerouslySetInnerHTML={{
                    __html: generateHighlightTextMarkup(
                      this.props.author.name,
                      this.props.highlightText
                    )
                  }}
                />
              </a>
              <div
                dangerouslySetInnerHTML={{
                  __html: `${this.props.author.bookCount} ${t(
                    "search/author/book"
                  )} `
                }}
              />
              <div
                dangerouslySetInnerHTML={{
                  __html: `${this.props.author.countSubscriber || "0"} ${t(
                    "search/author/subscriber"
                  )}`
                }}
              />
            </div>
            {this.props.author.isSubscribe !== null &&
            this.props.author.isOwner === false ? (
              <div className="AuthorItem__follow-button heavent">
                {this.props.author.isSubscribe ? (
                  <Button.Border
                    className="unfollow-button"
                    onClick={this.onclickRequestUnFollow}
                  >
                    {t("unfollow")}
                  </Button.Border>
                ) : (
                  <Button.Primary
                    className="follow-button"
                    onClick={this.onclickRequestFollow}
                  >
                    {t("follow")}
                  </Button.Primary>
                )}
              </div>
            ) : null}
          </AuthorItemContainer>
        )}
      </Analytic>
    )
  }
}

const updateAuthorSubscribeFragment = gql`
  fragment UpdateAuthorSubscribe on Author {
    isSubscribe
  }
`

const requestFollow = graphql<any, any, any, any>(
  gql`
    mutation($authorId: MongoID!) {
      requestFollow(authorId: $authorId)
    }
  `,
  {
    options: () => ({
      context: {
        service: "nap"
      },
      variables: {}
    }),
    props: ({ mutate }) => ({
      requestFollow: (_authorId) =>
        mutate &&
        mutate({
          update: (store, {}) => {
            store.writeFragment({
              id: getApolloId("Author", _authorId),
              fragment: updateAuthorSubscribeFragment,
              data: {
                __typename: "Author",
                isSubscribe: true
              }
            })
          },
          variables: {
            authorId: _authorId
          },
          optimisticResponse: {
            __typename: "Mutation",
            requestFollow: true
          }
        })
    })
  }
)

const requestUnFollow = graphql<any, any, any, any>(
  gql`
    mutation($authorId: MongoID!) {
      requestUnFollow(authorId: $authorId)
    }
  `,
  {
    options: () => ({
      context: {
        service: "nap"
      },
      variables: {}
    }),
    props: ({ mutate }) => ({
      requestUnFollow: (_authorId) =>
        mutate &&
        mutate({
          variables: {
            authorId: _authorId
          },
          optimisticResponse: {
            __typename: "Mutation",
            requestUnFollow: true
          },
          update: (store, {}) => {
            store.writeFragment({
              id: getApolloId("Author", _authorId),
              fragment: updateAuthorSubscribeFragment,
              data: {
                __typename: "Author",
                isSubscribe: false
              }
            })
          }
        })
    })
  }
)
export default compose(
  requestFollow,
  requestUnFollow
)(AuthorItemSubscribe as any)
