"use client";

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

function starLabel(n: number): string {
  return n === 1 ? "1 star" : `${n} stars`;
}

interface StarRatingScaleProps {
  min?: number;
  max?: number;
  value?: number | null;
  onChange?: (score: number) => void;
  /** Builder canvas — not clickable, still shows numbers so the scale is obvious. */
  preview?: boolean;
  className?: string;
}

export function StarRatingScale({
  min = 1,
  max = 5,
  value = null,
  onChange,
  preview = false,
  className,
}: StarRatingScaleProps) {
  const scores = Array.from(
    { length: Math.max(1, max - min + 1) },
    (_, i) => min + i
  );
  const [hovered, setHovered] = useState<number | null>(null);
  const litThrough = hovered ?? (typeof value === "number" ? value : null);
  const interactive = Boolean(onChange) && !preview;

  return (
    <div className={cn("mt-1", className)}>
      <div
        role={interactive ? "radiogroup" : undefined}
        aria-label="Star rating"
        className="flex flex-wrap gap-1.5"
        onMouseLeave={() => setHovered(null)}
      >
        {scores.map((n) => {
          const filled = litThrough != null && n <= litThrough;
          const selected = value === n;
          const inner = (
            <>
              <Star
                className={cn(
                  "h-5 w-5 shrink-0",
                  filled
                    ? "fill-amber-400 text-amber-400"
                    : "fill-none text-slate-300"
                )}
                strokeWidth={2}
              />
              <span
                className={cn(
                  "text-[11px] font-bold leading-none",
                  filled ? "text-navy" : "text-muted"
                )}
              >
                {starLabel(n)}
              </span>
            </>
          );

          const boxClass = cn(
            "flex min-w-[4.5rem] flex-1 flex-col items-center justify-center gap-1 rounded-md border px-1 py-2 transition-colors sm:min-w-[5.25rem]",
            filled
              ? "border-amber-300 bg-amber-50"
              : "border-border bg-white",
            selected && "ring-2 ring-primary/30",
            interactive && "cursor-pointer hover:border-amber-400"
          );

          if (!interactive) {
            return (
              <div key={n} className={boxClass}>
                {inner}
              </div>
            );
          }

          return (
            <button
              key={n}
              type="button"
              role="radio"
              aria-checked={selected}
              aria-label={starLabel(n)}
              onMouseEnter={() => setHovered(n)}
              onFocus={() => setHovered(n)}
              onBlur={() => setHovered(null)}
              onClick={() => onChange?.(n)}
              className={boxClass}
            >
              {inner}
            </button>
          );
        })}
      </div>
      <p className="mt-2 text-[11px] text-muted">
        {interactive
          ? `Tap a star. ${starLabel(min)} is lowest, ${starLabel(max)} is highest.`
          : `Respondents pick ${starLabel(min)} through ${starLabel(max)}. Stars fill up to the score they choose.`}
      </p>
    </div>
  );
}
