"use client";

import { useState, useTransition } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Heart, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { toggleWishlistAction } from "@/app/actions/account";
import { cn } from "@/lib/utils";

export function WishlistButton({
  productId,
  locale,
  initial,
  label,
  labelRemove,
  loginLabel = "",
  variant = "icon",
}: {
  productId: string;
  locale: string;
  initial: boolean;
  label: string;
  labelRemove: string;
  loginLabel?: string;
  variant?: "icon" | "full";
}) {
  const [active, setActive] = useState(initial);
  const [pending, startTransition] = useTransition();
  const router = useRouter();
  const pathname = usePathname();

  const toggle = () => {
    startTransition(async () => {
      const result = await toggleWishlistAction({ productId, locale });
      if (result.loginRequired) {
        toast.info(loginLabel || result.message);
        router.push(`/${locale}/login?callbackUrl=${encodeURIComponent(pathname)}`);
        return;
      }
      if (!result.ok) {
        toast.error(result.message);
        return;
      }
      setActive(Boolean(result.added));
      toast.success(result.added ? label : labelRemove);
    });
  };

  if (variant === "full") {
    return (
      <button
        type="button"
        onClick={toggle}
        disabled={pending}
        aria-busy={pending}
        className="flex w-full items-center justify-center gap-2 border border-charcoal/25 py-3 text-[12px] uppercase tracking-[0.16em] text-charcoal/70 transition-colors hover:border-charcoal hover:text-charcoal disabled:opacity-50"
      >
        {pending ? (
          <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.6} aria-hidden="true" />
        ) : (
          <Heart className={cn("h-3.5 w-3.5", active && "fill-terracotta text-terracotta")} strokeWidth={1.5} />
        )}
        {active ? labelRemove : label}
      </button>
    );
  }

  return (
    <button
      type="button"
      onClick={toggle}
      disabled={pending}
      aria-busy={pending}
      aria-label={active ? labelRemove : label}
      className={cn(
        "flex h-10 w-10 items-center justify-center border border-charcoal/15 bg-cream/80 text-charcoal/60 backdrop-blur transition-colors hover:border-charcoal hover:text-charcoal disabled:opacity-50",
      )}
    >
      {pending ? (
        <Loader2 className="h-4 w-4 animate-spin" strokeWidth={1.6} aria-hidden="true" />
      ) : (
        <Heart className={cn("h-4 w-4", active && "fill-terracotta text-terracotta")} strokeWidth={1.4} />
      )}
    </button>
  );
}
