"use client";

import Image from "next/image";
import { useState } from "react";
import { dispatchStorefrontCartUpdated } from "@/lib/storefront-events";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import type { StorefrontCart, StorefrontProductCard } from "@/types/storefront";

export function ProductCardAddButton({
  product,
}: {
  product: StorefrontProductCard;
}) {
  const [isAdding, setIsAdding] = useState(false);

  async function handleAddToCart() {
    try {
      setIsAdding(true);

      const response = await fetch("/api/cart/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: product.id,
          quantity: 1,
        }),
      });

      const payload = (await response.json()) as StorefrontCart | { message?: string };

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

      dispatchStorefrontCartUpdated(payload as StorefrontCart, "add-item");
    } finally {
      setIsAdding(false);
    }
  }

  return (
    <button
      type="button"
      onClick={handleAddToCart}
      disabled={isAdding || !product.isInStock}
      className="inline-flex size-9 cursor-pointer items-center justify-center rounded-[6px] bg-accent text-white disabled:cursor-not-allowed disabled:opacity-60"
      aria-label="Dodaj u košaricu"
    >
      <Image
        src={detonexFigmaAssets.icons.cartSmall}
        alt=""
        width={18}
        height={18}
        className="size-[18px]"
      />
    </button>
  );
}
