"use client";

import { useState } from "react";
import { vibrate } from "@/lib/haptics";

interface FavoriteButtonProps {
  userId: number;
  isFavorited?: boolean;
  onToggle?: (isFavorited: boolean) => void;
}

export default function FavoriteButton({
  userId,
  isFavorited: initialFavorited = false,
  onToggle,
}: FavoriteButtonProps) {
  const [isFavorited, setIsFavorited] = useState(initialFavorited);
  const [isLoading, setIsLoading] = useState(false);

  const handleToggle = async () => {
    setIsLoading(true);
    // Optimistic flip — roll back on failure so users see real state.
    const optimistic = !isFavorited;
    setIsFavorited(optimistic);
    try {
      const res = await fetch("/api/favorites", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          markable_type: "App\\Models\\User",
          markable_id: userId,
        }),
      });

      if (!res.ok) throw new Error("Failed to toggle favorite");

      const data = await res.json();
      const newState = data.toggled === "added";
      setIsFavorited(newState);
      vibrate(newState ? [10, 30, 10] : 10);
      onToggle?.(newState);
    } catch (error) {
      // Roll back the optimistic flip; surface the error so users notice.
      setIsFavorited(!optimistic);
      console.error("Toggle favorite error:", error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <button
      onClick={handleToggle}
      disabled={isLoading}
      className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50 ${
        isFavorited
          ? "bg-pink-600 text-white hover:bg-pink-700"
          : "bg-zinc-800 text-zinc-300 hover:bg-zinc-700"
      }`}
    >
      <svg
        className="h-4 w-4"
        fill={isFavorited ? "currentColor" : "none"}
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
        />
      </svg>
      {isFavorited ? "Favorited" : "Favorite"}
    </button>
  );
}
