"use client";

import React, { useState } from "react";
import { Star } from "lucide-react";
import { WebTypeComponentProps } from "@/lib/registry/types";

export interface RatingWidgetProps extends WebTypeComponentProps {
  maxRating?: number;
  allowHalf?: boolean;
  size?: "sm" | "md" | "lg";
}

export const RatingWidget: React.FC<RatingWidgetProps> = ({
  value = 0,
  onChange,
  onEvent,
  disabled = false,
  readonly = false,
  placeholder = "별점을 선택하세요",
  className = "",
  webTypeConfig = {},
  maxRating = 5,
  allowHalf = false,
  size = "md",
  ...props
}) => {
  const [hoverRating, setHoverRating] = useState<number>(0);
  const [currentRating, setCurrentRating] = useState<number>(Number(value) || 0);

  // 웹타입 설정에서 값 가져오기
  const finalMaxRating = webTypeConfig.maxRating || maxRating;
  const finalAllowHalf = webTypeConfig.allowHalf ?? allowHalf;
  const finalSize = webTypeConfig.size || size;

  // 크기별 스타일
  const sizeClasses = {
    sm: "h-4 w-4",
    md: "h-5 w-5",
    lg: "h-6 w-6",
  };

  const handleStarClick = (rating: number) => {
    if (disabled || readonly) return;

    setCurrentRating(rating);
    onChange?.(rating);
    onEvent?.("change", { value: rating, webType: "rating" });
  };

  const handleStarHover = (rating: number) => {
    if (disabled || readonly) return;
    setHoverRating(rating);
  };

  const handleMouseLeave = () => {
    setHoverRating(0);
  };

  const renderStars = () => {
    const stars = [];
    const displayRating = hoverRating || currentRating;

    for (let i = 1; i <= finalMaxRating; i++) {
      const isFilled = i <= displayRating;
      const isHalfFilled = finalAllowHalf && i - 0.5 <= displayRating && i > displayRating;

      stars.push(
        <button
          key={i}
          type="button"
          className={` ${sizeClasses[finalSize]} transition-colors duration-150 ${disabled || readonly ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:scale-110"} ${isFilled ? "text-yellow-400" : "text-muted-foreground/50"} `}
          onClick={() => handleStarClick(i)}
          onMouseEnter={() => handleStarHover(i)}
          disabled={disabled || readonly}
        >
          <Star className={`${sizeClasses[finalSize]} ${isFilled ? "fill-current" : ""}`} />
        </button>,
      );
    }

    return stars;
  };

  return (
    <div className={`flex items-center gap-1 ${className}`} onMouseLeave={handleMouseLeave} {...props}>
      {/* 별점 표시 */}
      <div className="flex items-center gap-0.5">{renderStars()}</div>

      {/* 현재 점수 표시 */}
      {!readonly && (
        <span className="ml-2 text-sm text-muted-foreground">
          {currentRating > 0 ? `${currentRating}/${finalMaxRating}` : placeholder}
        </span>
      )}

      {/* 숨겨진 input (폼 제출용) */}
      <input type="hidden" name={props.name} value={currentRating} />
    </div>
  );
};

RatingWidget.displayName = "RatingWidget";
