import * as React from "react"
import { StarIndicator } from "../Book/RatingStarIndicator"
import styled from "styled-components"

const RatingStarInputStyle = styled.div`
  .StarIndicator {
    display: flex;
    font-size: 2rem;
    color: ${(props) => props.theme.pumpkin};
  }
`

type RatingStarInputInputPropTypes = {
  value: number
  onStarClick: (index: number) => void
  onStarMouseLeave: () => void
  onStarMouseEnter: (index: number) => void
}

type RatingStarInputComponent = React.SFC<RatingStarInputInputPropTypes>
const RatingStarInputComponent: RatingStarInputComponent = (props) => {
  return (
    <RatingStarInputStyle>
      <StarIndicator
        average={props.value}
        count={1}
        onClick={props.onStarClick}
        onMouseLeave={props.onStarMouseLeave}
        onMouseEnter={props.onStarMouseEnter}
      />
    </RatingStarInputStyle>
  )
}

export class RatingStarInput extends React.Component<
  { value?: number; onChange?: (ratingResult: number) => void },
  { hoverValue: number }
> {
  public static defaultProps = {
    value: 0,
    onChange: (s) => s
  }
  constructor(props) {
    super(props)
    this.state = {
      hoverValue: props.value
    }
  }

  public onStarMouseLeave = () => {
    // reset to last commit value
    this.setState({
      hoverValue: this.props.value || 0
    })
  }

  public onStarMouseEnter = (index: number) => {
    this.setState({
      hoverValue: index
    })
  }

  public onStarClick = (index: number) => {
    if (this.props.onChange) {
      this.props.onChange(index)
    }
  }

  public render() {
    return (
      <RatingStarInputComponent
        value={this.state.hoverValue}
        onStarClick={this.onStarClick}
        onStarMouseLeave={this.onStarMouseLeave}
        onStarMouseEnter={this.onStarMouseEnter}
      />
    )
  }
}

export default RatingStarInput
