"use client";

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

export function RatingStars({
  recipeId,
  initialScore = 0,
  readonly = false,
  size = "default",
}: {
  recipeId: string;
  initialScore?: number;
  readonly?: boolean;
  size?: "sm" | "default";
}) {
  const [score, setScore] = useState(initialScore);
  const [hovered, setHovered] = useState(0);
  const [saving, setSaving] = useState(false);

  async function rate(value: number) {
    if (readonly || saving) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/v1/recipes/${recipeId}/rate`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ score: value }),
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        toast.error(err.error ?? "Failed to rate");
        return;
      }
      setScore(value);
      toast.success("Rating saved");
    } finally {
      setSaving(false);
    }
  }

  const iconSize = size === "sm" ? "h-3.5 w-3.5" : "h-5 w-5";
  const display = hovered || score;

  return (
    <div className={cn("flex items-center gap-0.5", readonly && "pointer-events-none")}>
      {[1, 2, 3, 4, 5].map((i) => (
        <button
          key={i}
          type="button"
          disabled={readonly || saving}
          onMouseEnter={() => !readonly && setHovered(i)}
          onMouseLeave={() => !readonly && setHovered(0)}
          onClick={() => rate(i)}
          className={cn("transition-colors", !readonly && "hover:scale-110")}
        >
          <Star
            className={cn(
              iconSize,
              i <= display ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground/30"
            )}
          />
        </button>
      ))}
    </div>
  );
}
