import * as React from "react"
import styled from "styled-components"
import Icon from "../../icon"
import withTranslate from "jamplay-common/i18n/withTranslate"

const RatingStarContainer = styled.div.attrs({
  className: "RatingStarContainer"
})`
  display: flex;
  align-items: center;
  span {
    white-space: pre;
  }
  .RatingStarIndicator--stars-container {
    display: inline-block;
    margin-top: 4px;
    margin-right: 5px;
    color: ${(props: any) => props.theme.pumpkin};
    .jamplay-icon {
      display: inline-block;
      padding-bottom: 4px;
    }
  }
`
export function getStars(
  _count,
  onClick: (index) => void = (s) => s,
  onMouseEnter: (index) => void = (s) => s
) {
  const count = Math.round(_count)
  const stars: any[] = []

  const click = (i) => () => onClick(i + 1)
  const enter = (i) => () => onMouseEnter(i + 1)

  let starCount = 0

  for (let i = 0; i < count; i++) {
    stars.push(
      <Icon
        key={i}
        name="star"
        onMouseEnter={enter(starCount)}
        onClick={click(starCount)}
      />
    )
    starCount++
  }
  for (let i = 0; i < 5 - count; i++) {
    stars.push(
      <Icon
        key={"o" + i}
        name="star-o"
        onClick={click(starCount)}
        onMouseEnter={enter(starCount)}
      />
    )
    starCount++
  }
  return stars
}

type StarIndicatorPropTypes = {
  count: any
  average: any

  onMouseEnter?: (index: number) => void
  onMouseLeave?: () => void
  onClick?: (index: number) => void
}
export const StarIndicator: React.SFC<StarIndicatorPropTypes> = (props) => {
  const { count, average, onClick, onMouseEnter, onMouseLeave } = props
  return count > 0 ? (
    <div
      className="StarIndicator RatingStarIndicator--stars-container"
      onMouseLeave={onMouseLeave}
    >
      {getStars(average, onClick, onMouseEnter)}
    </div>
  ) : null
}
StarIndicator.displayName = "StarIndicator"

interface RatingStarIndicatorPropType extends withTranslatePropType {
  average: any
  count: any
}
export class RatingStarIndicator extends React.Component<
  RatingStarIndicatorPropType,
  {}
> {
  public render() {
    let { t } = this.props
    if (!t) {
      t = (s) => s
    }

    return (
      <RatingStarContainer>
        <StarIndicator average={this.props.average} count={this.props.count} />
        {this.props.count > 0 ? (
          <span
            className="RatingStarContainer__label"
            style={{ paddingBottom: 3 }}
          >
            {`${this.props.count} ` + t("book/reviews")}
          </span>
        ) : (
          <span style={{ paddingBottom: 6 }}>
            {/* {this.props.t('book/reviews-is-not-enough-to-show')} */}
          </span>
        )}
      </RatingStarContainer>
    )
  }
}

export default withTranslate(RatingStarIndicator) as React.ComponentClass<
  RatingStarIndicatorPropType
>
