import React, { useState } from 'react'
import { LuStar } from 'react-icons/lu'

interface StarRatingProps {
  /** The current rating value (1-5) */
  value?: number
  /** Maximum number of stars to display */
  maxStars?: number
  /** Whether the rating can be changed by the user */
  interactive?: boolean
  /** Size of stars in pixels */
  size?: number
  /** Color of filled stars */
  fillColor?: string
  /** Color of empty stars */
  emptyColor?: string
  /** Optional class name for the container */
  className?: string
  /** Called when rating changes (only in interactive mode) */
  onChange?: (rating: number) => void
  /** Whether to show the numerical rating next to stars */
  showValue?: boolean
  /** Number of decimal places to show when displaying value */
  precision?: number
  /** Step size for interactive ratings (0.5 for half stars, 0.1 for tenths, etc.) */
  step?: number
}

export default function StarRating({
  value = 0,
  maxStars = 5,
  interactive = false,
  size = 24,
  fillColor = '#fb923c', // Gold color
  emptyColor = '#E5E7EB', // Light gray
  className = '',
  onChange,
  showValue = false,
  precision = 1,
  step = 1,
}: StarRatingProps) {
  const [hoverRating, setHoverRating] = useState(0)
  const [isHovering, setIsHovering] = useState(false)

  // Calculate the display rating (either hovered rating or actual value)
  const displayRating = isHovering ? hoverRating : value

  // Handle mouse enter on a star
  const handleMouseEnter = (rating: number, e: React.MouseEvent) => {
    if (!interactive) return

    // For partial star ratings based on mouse position
    if (step < 1) {
      const rect = e.currentTarget.getBoundingClientRect()
      const starWidth = rect.width
      const offsetX = e.clientX - rect.left
      const percentage = offsetX / starWidth

      // Calculate precise rating based on step
      let preciseRating = rating - 1 + percentage
      // Round to nearest step (e.g., 0.1 or 0.5)
      preciseRating = Math.round(preciseRating / step) * step
      // Ensure it's within valid range
      preciseRating = Math.max(Math.min(preciseRating, rating), rating - 1)

      setIsHovering(true)
      setHoverRating(preciseRating)
    } else {
      setIsHovering(true)
      setHoverRating(rating)
    }
  }

  // Handle mouse move within a star for partial ratings
  const handleMouseMove = (rating: number, e: React.MouseEvent) => {
    if (!interactive || step >= 1) return

    const rect = e.currentTarget.getBoundingClientRect()
    const starWidth = rect.width
    const offsetX = e.clientX - rect.left
    const percentage = offsetX / starWidth

    // Calculate precise rating based on step
    let preciseRating = rating - 1 + percentage
    // Round to nearest step (e.g., 0.1 or 0.5)
    preciseRating = Math.round(preciseRating / step) * step
    // Ensure it's within valid range
    preciseRating = Math.max(Math.min(preciseRating, rating), rating - 1)

    setHoverRating(preciseRating)
  }

  // Handle mouse leave from the component
  const handleMouseLeave = () => {
    if (!interactive) return
    setIsHovering(false)
    setHoverRating(0)
  }

  // Handle click on a star
  const handleClick = (rating: number, e: React.MouseEvent) => {
    if (!interactive || !onChange) return

    if (step < 1) {
      const rect = e.currentTarget.getBoundingClientRect()
      const starWidth = rect.width
      const offsetX = e.clientX - rect.left
      const percentage = offsetX / starWidth

      // Calculate precise rating based on step
      let preciseRating = rating - 1 + percentage
      // Round to nearest step (e.g., 0.1 or 0.5)
      preciseRating = Math.round(preciseRating / step) * step
      // Ensure it's within valid range
      preciseRating = Math.max(Math.min(preciseRating, rating), rating - 1)

      onChange(preciseRating)
    } else {
      onChange(rating)
    }
  }

  // Function to get fill color based on rating and position
  const getStarFill = (position: number) => {
    // For whole stars (position is less than or equal to the rating)
    if (position <= displayRating) {
      return fillColor
    }
    // For partial stars (when position is greater than rating but within 1)
    else if (position - 1 < displayRating) {
      // Calculate the percentage to fill (0.3 for 4.3 when position is 5)
      const fillPercentage = (displayRating - Math.floor(displayRating)) * 100
      return `url(#partialGradient-${position}-${fillPercentage.toFixed(0)})`
    }
    return 'none'
  }

  // Generate stars
  const renderStars = () => {
    const stars: React.JSX.Element[] = []

    for (let i = 1; i <= maxStars; i++) {
      stars.push(
        <div
          key={i}
          className={`inline-block ${interactive ? 'cursor-pointer' : ''}`}
          onMouseEnter={(e) => handleMouseEnter(i, e)}
          onMouseMove={(e) => handleMouseMove(i, e)}
          onClick={(e) => handleClick(i, e)}
          role={interactive ? 'button' : undefined}
          aria-label={
            interactive ? `Rate ${i} out of ${maxStars} stars` : undefined
          }
        >
          <LuStar
            size={size}
            fill={getStarFill(i)}
            stroke={emptyColor}
            strokeWidth={1.5}
            className="transition-colors duration-150"
          />

          {/* This SVG gradient enables partial star rendering */}
          <svg style={{ width: 0, height: 0, position: 'absolute' }}>
            <defs>
              {/* Create a dynamic gradient based on the actual percentage */}
              {Array.from({ length: 101 }, (_, index) => {
                const percentage = index
                return (
                  <linearGradient
                    key={percentage}
                    id={`partialGradient-${i}-${percentage}`}
                    x1="0%"
                    y1="0%"
                    x2="100%"
                    y2="0%"
                  >
                    <stop offset={`${percentage}%`} stopColor={fillColor} />
                    <stop
                      offset={`${percentage}%`}
                      stopColor="rgba(255,255,255,0)"
                    />
                  </linearGradient>
                )
              })}
            </defs>
          </svg>
        </div>,
      )
    }

    return stars
  }

  return (
    <div
      className={`flex items-center gap-1 ${className}`}
      onMouseLeave={handleMouseLeave}
      aria-label={`Rating: ${value} out of ${maxStars} stars`}
    >
      {renderStars()}

      {showValue && (
        <span className="ml-2 text-sm font-medium">
          {value.toFixed(precision)}
        </span>
      )}
    </div>
  )
}
