"use client";

import { useState, useEffect, useCallback } from "react";
import { ShoppingCart, Check } from "lucide-react";
import { useTranslations } from "next-intl";

interface AddToCartBtnProps {
  onClick?: (e: React.MouseEvent) => void;
  label?: string;
  icon?: React.ReactNode;
  disabled?: boolean;
  className?: string;
  /** Set to true externally after a successful add */
  showSuccess?: boolean;
}

/**
 * Add-to-Cart button with tactile click animation and
 * a checkmark-morph success state.
 */
export default function AddToCartBtn({
  onClick,
  label,
  icon,
  disabled = false,
  className = "",
  showSuccess = false,
}: AddToCartBtnProps) {
  const t = useTranslations("products");
  const resolvedLabel = label || t("add-to-cart");
  const [isPressed, setIsPressed] = useState(false);
  const [successVisible, setSuccessVisible] = useState(false);

  // Show success checkmark for 1.5s after add completes
  useEffect(() => {
    if (showSuccess) {
      setSuccessVisible(true);
      const timer = setTimeout(() => setSuccessVisible(false), 1500);
      return () => clearTimeout(timer);
    }
  }, [showSuccess]);

  const handleClick = useCallback(
    (e: React.MouseEvent) => {
      // Tactile press animation
      setIsPressed(true);
      setTimeout(() => setIsPressed(false), 150);
      onClick?.(e);
    },
    [onClick]
  );

  return (
    <button
      onClick={handleClick}
      disabled={disabled}
      className={`
        w-full h-12 rounded-s flex items-center justify-center gap-2.5
        border-2 transition-all duration-200
        disabled:opacity-50 disabled:cursor-not-allowed
        ${successVisible
          ? "bg-emerald-50 border-emerald-400 text-emerald-700"
          : "bg-white border-gray-300 text-gray-800 hover:bg-gray-50 hover:border-gray-400"
        }
        ${className}
      `}
      style={{
        transform: isPressed ? "scale(0.96)" : "scale(1)",
        transition: "transform 150ms ease-out, background-color 200ms, border-color 200ms, color 200ms",
      }}
      aria-label={resolvedLabel}
    >
      <span className="text-[15px] font-bold">
        {successVisible ? t("added-to-cart") : resolvedLabel}
      </span>

      {successVisible ? (
        <Check
          className="w-5 h-5 text-emerald-600 animate-[cart-check-pop_0.3s_ease-out]"
          strokeWidth={3}
        />
      ) : (
        icon || <ShoppingCart className="w-5 h-5" strokeWidth={2.5} />
      )}

      {/* Inline keyframes for the checkmark pop-in */}
      <style jsx>{`
        @keyframes cart-check-pop {
          0% { transform: scale(0) rotate(-45deg); opacity: 0; }
          60% { transform: scale(1.2) rotate(0deg); opacity: 1; }
          100% { transform: scale(1) rotate(0deg); opacity: 1; }
        }
      `}</style>
    </button>
  );
}
