import React, { memo, useMemo, useState } from "react";
import { Bar, BarTitle, StarContainer } from "./styled";
import { Star } from "./star";
import { isNil } from "lodash-es";

interface StarRatingProps {
  value?: number;
  onChange?: (value: number) => void;
  style?: React.CSSProperties;
}

export const StarRating: React.FC<StarRatingProps> = memo(props => {
  const { value, onChange, style } = props;
  const starNums = [1, 2, 3, 4, 5];
  const [mouseOnStar, setMouseOnStar] = useState<number | undefined>(undefined);
  const displayNumber = useMemo(() => {
    return !isNil(mouseOnStar) ? mouseOnStar : value;
  }, [value, mouseOnStar]);

  return (
    <Bar style={style}>
      <BarTitle>反馈：</BarTitle>
      <StarContainer>
        {starNums.map(number => {
          return (
            <Star
              style={{
                padding: "0 4px",
              }}
              active={Boolean(displayNumber && displayNumber >= number)}
              key={`star-${number}`}
              onMouseEnter={() => {
                setMouseOnStar(number);
              }}
              onMouseLeave={() => {
                setMouseOnStar(undefined);
              }}
              onMouseDown={() => {
                onChange && onChange(number);
              }}
            />
          );
        })}
      </StarContainer>
    </Bar>
  );
});
