import { useRef, type ReactNode, type MouseEvent } from 'react';

interface Props {
  children: ReactNode;
  href?: string;
  onClick?: () => void;
  className?: string;
  target?: string;
  rel?: string;
  strength?: number;
  download?: boolean | string;
}

export default function MagneticButton({
  children,
  href,
  onClick,
  className = '',
  target,
  rel,
  strength = 0.3,
  download,
}: Props) {
  const ref = useRef<HTMLElement | null>(null);

  function handleMove(e: MouseEvent) {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia('(pointer: coarse)').matches) return;
    const rect = el.getBoundingClientRect();
    const x = e.clientX - (rect.left + rect.width / 2);
    const y = e.clientY - (rect.top + rect.height / 2);
    el.style.transform = `translate(${x * strength}px, ${y * strength}px)`;
  }

  function handleLeave() {
    if (!ref.current) return;
    ref.current.style.transform = '';
  }

  const baseClass = `inline-block transition-transform duration-200 ease-out will-change-transform ${className}`;

  if (href) {
    return (
      <a
        ref={ref as React.RefObject<HTMLAnchorElement>}
        href={href}
        target={target}
        rel={rel}
        download={download as boolean | string | undefined}
        onMouseMove={handleMove}
        onMouseLeave={handleLeave}
        className={baseClass}
      >
        {children}
      </a>
    );
  }
  return (
    <button
      ref={ref as React.RefObject<HTMLButtonElement>}
      type="button"
      onMouseMove={handleMove}
      onMouseLeave={handleLeave}
      onClick={onClick}
      className={baseClass}
    >
      {children}
    </button>
  );
}
