"use client";

import { useState, useTransition } from "react";
import { CheckCircle2, Loader2, ShoppingCart } from "lucide-react";
import { addToCart } from "@/app/products/store/cart/actions";

type Props = {
  productId: string;
  disabled?: boolean;
  label?: string;
};

/**
 * Client island — Add-to-cart button. Posts to the server action and
 * briefly flips to a success state so the user knows something happened
 * without a full navigation.
 */
export function AddToCartForm({ productId, disabled, label = "Add to cart" }: Props) {
  const [pending, startTransition] = useTransition();
  const [justAdded, setJustAdded] = useState(false);

  function handleSubmit(formData: FormData) {
    startTransition(async () => {
      await addToCart(formData);
      setJustAdded(true);
      window.setTimeout(() => setJustAdded(false), 2500);
    });
  }

  return (
    <form action={handleSubmit} className="flex flex-wrap items-center gap-2">
      <input type="hidden" name="productId" value={productId} />
      <div className="flex items-center gap-1 rounded-md border border-[var(--color-line)] bg-white">
        <QuantityInput />
      </div>
      <button
        type="submit"
        disabled={disabled || pending}
        className="inline-flex items-center gap-2 rounded-lg bg-[var(--color-blue)] px-4 py-2 text-[13px] font-semibold text-white shadow-sm transition-opacity hover:opacity-95 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
            Adding…
          </>
        ) : justAdded ? (
          <>
            <CheckCircle2 className="h-4 w-4" aria-hidden />
            Added to cart
          </>
        ) : (
          <>
            <ShoppingCart className="h-4 w-4" aria-hidden />
            {label}
          </>
        )}
      </button>
    </form>
  );
}

function QuantityInput() {
  return (
    <label className="flex items-center">
      <span className="sr-only">Quantity</span>
      <input
        name="quantity"
        type="number"
        defaultValue={1}
        min={1}
        max={10}
        className="w-14 border-0 bg-transparent px-3 py-2 text-[13px] text-[var(--color-ink)] focus:outline-none"
      />
    </label>
  );
}
