"use client";

import { useState } from "react";
import {
  FetchError,
  apiPost,
  apiDelete,
} from "@/lib/client-api";

export function FavoriteTemplateButton({
  templateId,
  initialFavorited,
  className,
}: {
  templateId: string;
  initialFavorited: boolean;
  className?: string;
}) {
  const [favorited, setFavorited] = useState(initialFavorited);
  const [pending, setPending] = useState(false);

  const toggle = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (pending) return;
    const next = !favorited;
    setFavorited(next);
    setPending(true);
    try {
      if (next) {
        await apiPost("/api/favorites", { templateId });
      } else {
        await apiDelete(`/api/favorites/${templateId}`);
      }
    } catch (err) {
      setFavorited(!next);
      const msg = err instanceof FetchError ? err.message : "Action failed.";
      console.warn(msg);
    } finally {
      setPending(false);
    }
  };

  return (
    <button
      type="button"
      onClick={toggle}
      disabled={pending}
      aria-label={favorited ? "Remove from favorites" : "Add to favorites"}
      aria-pressed={favorited}
      className={
        "grid h-9 w-9 place-items-center rounded-full border bg-transparent transition-all hover:scale-110 disabled:opacity-60 " +
        (favorited
          ? "border-rose-500 text-rose-500 shadow-[0_0_14px_rgba(244,63,94,0.55)]"
          : "border-rose-300 text-rose-400 hover:border-rose-400 hover:text-rose-500") +
        (className ? ` ${className}` : "")
      }
    >
      <svg
        viewBox="0 0 24 24"
        className="h-5 w-5"
        fill={favorited ? "currentColor" : "none"}
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        <path d="M12 21s-7.5-4.6-9.6-9.4C.7 7.5 3.5 4 7 4c2 0 3.6 1 5 2.6C13.4 5 15 4 17 4c3.5 0 6.3 3.5 4.6 7.6C19.5 16.4 12 21 12 21Z" />
      </svg>
    </button>
  );
}
