import React from 'react'

import Icon from '../Icons/Icon'
import styles from './_review-stars.module.scss'

export type ReviewStarsProps = {
  rating: number
  className?: string
  /** Optional prop to add a test id to the ReviewStars for QA testing */
  qaTestId?: string
}

const ReviewStars = ({
  rating,
  className = '',
  qaTestId = 'review-stars',
}: ReviewStarsProps): React.JSX.Element => {
  const getStarIcon = (
    index: number,
    fullStars: number,
    hasHalfStar: boolean,
  ): React.JSX.Element => {
    if (index < fullStars) {
      return <Icon icon='starSolid' className={styles.fullStar} />
    }
    return hasHalfStar && index === fullStars ? (
      <Icon icon='starHalfSolid' />
    ) : (
      <Icon icon='starSolid' className={styles.emptyStar} />
    )
  }
  const decimalValue = Number((rating % 1).toFixed(2))
  const fullStars = Math.floor(rating) + Number(decimalValue >= 0.8)
  const hasHalfStar = decimalValue >= 0.3 && decimalValue < 0.8
  return (
    <div
      className={`${styles.starsContainer} ${className}`}
      qa-test-id={qaTestId}
    >
      {Array.from({ length: 5 }, (_, index) => (
        <div key={index}>{getStarIcon(index, fullStars, hasHalfStar)}</div>
      ))}
    </div>
  )
}

export default ReviewStars
