import React, { useState, useCallback } from "react";
import { Star } from "lucide-react";
import { cn } from "@/shared/lib/utils";

export interface StarRatingProps {
  value?: number;
  onChange?: (rating: number) => void;
  maxRating?: number;
  size?: "sm" | "md" | "lg";
  disabled?: boolean;
  showLabels?: boolean;
  className?: string;
  labels?: string[];
  language?: "am" | "en";
}

const defaultLabelsEn = ["Very Poor", "Poor", "Normal", "Good", "Excellent"];
const defaultLabelsAm = ["በጣም መጥፎ", "መጥፎ", "መካከለኛ", "ጥሩ", "በጣም ጥሩ"];

export const StarRating: React.FC<StarRatingProps> = ({
  value = 0,
  onChange,
  maxRating = 5,
  size = "md",
  disabled = false,
  showLabels = true,
  className,
  labels,
  language = "en",
}) => {
  // Use provided labels or default based on language
  const ratingLabels =
    labels || (language === "am" ? defaultLabelsAm : defaultLabelsEn);
  const [hoverRating, setHoverRating] = useState(0);
  const [isHovering, setIsHovering] = useState(false);

  const sizeClasses = {
    sm: "w-4 h-4",
    md: "w-6 h-6",
    lg: "w-8 h-8",
  };

  const handleStarClick = useCallback(
    (rating: number) => {
      if (!disabled && onChange) {
        // Use requestAnimationFrame to prevent vibration
        requestAnimationFrame(() => {
          onChange(rating);
        });
      }
    },
    [disabled, onChange]
  );

  const handleStarHover = useCallback(
    (rating: number) => {
      if (!disabled) {
        if (!isHovering || rating !== hoverRating) {
          setHoverRating(rating);
          setIsHovering(true);
        }
      }
    },
    [disabled, isHovering, hoverRating]
  );

  const handleMouseLeave = useCallback(() => {
    if (isHovering) {
      setIsHovering(false);
      setHoverRating(0);
    }
  }, [isHovering]);

  const displayRating = isHovering ? hoverRating : value;
  const currentLabel = ratingLabels[displayRating - 1] || "";

  return (
    <div
      className={cn("flex flex-col items-center gap-4", className)}
      style={{
        backfaceVisibility: "hidden",
        transform: "translateZ(0)",
        willChange: "auto",
      }}
    >
      <div
        className="flex items-center justify-center gap-2"
        onMouseLeave={handleMouseLeave}
        style={{
          backfaceVisibility: "hidden",
          transform: "translateZ(0)",
        }}
      >
        {Array.from({ length: maxRating }, (_, index) => {
          const starRating = index + 1;
          const isFilled = starRating <= displayRating;

          return (
            <button
              key={index}
              type="button"
              className={cn(
                "relative flex items-center justify-center transition-colors duration-150 ease-out focus:outline-none focus:ring-2 focus:ring-primary/20 rounded-lg p-2",
                disabled
                  ? "cursor-not-allowed opacity-50"
                  : "cursor-pointer hover:bg-yellow-50/30"
              )}
              onClick={() => handleStarClick(starRating)}
              onMouseEnter={() => handleStarHover(starRating)}
              disabled={disabled}
              style={{
                touchAction: "manipulation",
                backfaceVisibility: "hidden",
                transform: "translate3d(0, 0, 0)",
                WebkitFontSmoothing: "antialiased",
                minWidth: "3rem",
                minHeight: "3rem",
              }}
            >
              <Star
                className={cn(
                  sizeClasses[size],
                  "transition-colors duration-150 ease-out",
                  isFilled
                    ? "fill-yellow-400 text-yellow-400"
                    : "fill-transparent text-gray-300"
                )}
                style={{
                  backfaceVisibility: "hidden",
                  transform: "translate3d(0, 0, 0)",
                  WebkitFontSmoothing: "antialiased",
                }}
              />
            </button>
          );
        })}
      </div>

      {showLabels && (
        <div className="text-center min-h-[2.5rem] flex items-center justify-center">
          {displayRating > 0 && (
            <div className="text-lg font-semibold text-gray-800 bg-yellow-50 px-4 py-2 rounded-full border border-yellow-200 transition-opacity duration-150">
              {currentLabel}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default StarRating;
