"use client";

import Image from "next/image";
import { useState } from "react";
import {
  dispatchStorefrontWishlistAdded,
  dispatchStorefrontWishlistUpdated,
} from "@/lib/storefront-events";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import type { StorefrontWishlist, StorefrontWishlistItem } from "@/types/storefront";

export function ProductCardWishlistButton({
  item,
}: {
  item: StorefrontWishlistItem;
}) {
  const [isPending, setIsPending] = useState(false);

  async function handleAddToWishlist() {
    try {
      setIsPending(true);

      const response = await fetch("/api/wishlist/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(item),
      });
      const payload = (await response.json()) as StorefrontWishlist | { message?: string };

      if (!response.ok) {
        throw new Error(
          "message" in payload && payload.message
            ? payload.message
            : "Dodavanje u listu želja nije uspjelo.",
        );
      }

      dispatchStorefrontWishlistUpdated(payload as StorefrontWishlist);
      dispatchStorefrontWishlistAdded(item);
    } catch {
      // Keep the card button quiet on failure; the count and toast only update after success.
    } finally {
      setIsPending(false);
    }
  }

  return (
    <button
      type="button"
      aria-label="Dodaj u listu želja"
      className="absolute right-5 top-5 inline-flex size-[34px] cursor-pointer items-center justify-center rounded-full border border-line bg-white text-primary"
      onClick={handleAddToWishlist}
      disabled={isPending}
    >
      <Image
        src={detonexFigmaAssets.icons.heartSmall}
        alt=""
        width={16}
        height={16}
        className="size-4"
      />
    </button>
  );
}
