"use client";

import React, { useRef, useState } from "react";
import { m, LazyMotion, domAnimation } from "framer-motion";
import Link from "next/link";
import { ArrowRight } from "lucide-react";

interface ButtonProps {
  children: React.ReactNode;
  href?: string;
  onClick?: () => void;
  variant?: "primary" | "accent" | "outline" | "ghost";
  className?: string;
  showArrow?: boolean;
  type?: "button" | "submit" | "reset";
  disabled?: boolean;
}

export const Button = ({
  children,
  href,
  onClick,
  variant = "primary",
  className = "",
  showArrow = false,
  type = "button",
  disabled = false,
}: ButtonProps) => {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseMove = (e: React.MouseEvent) => {
    const rect = e.currentTarget.getBoundingClientRect();
    setMousePosition({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
  };

  const baseStyles =
    "inline-flex items-center justify-center px-6 py-4 md:px-10 md:py-5 rounded-xl md:rounded-2xl font-bold uppercase tracking-[0.2em] text-[10px] transition-all duration-500 relative group cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed select-none overflow-hidden";

  const variants = {
    primary: "bg-primary text-white shadow-lg",
    accent: "bg-accent text-white shadow-lg",
    outline:
      "border-2 border-primary text-primary hover:bg-primary hover:text-white",
    ghost: "bg-slate-100 text-primary hover:bg-slate-200",
  };

  const content = (
    <span className="relative z-10 flex items-center gap-3">
      {children}
      {showArrow && (
        <ArrowRight
          size={14}
          strokeWidth={3}
          className="group-hover:translate-x-1 transition-transform duration-300"
        />
      )}
    </span>
  );

  const spotlight = (
    <LazyMotion features={domAnimation}>
      <m.div
        className="absolute inset-0 z-0 pointer-events-none transition-opacity duration-500"
        style={{
          opacity: isHovered ? 1 : 0,
          background: `radial-gradient(600px circle at ${mousePosition.x}px ${mousePosition.y}px, rgba(255,255,255,0.15), transparent 40%)`,
        }}
      />
    </LazyMotion>
  );

  const buttonProps = {
    onMouseMove: handleMouseMove,
    onMouseEnter: () => setIsHovered(true),
    onMouseLeave: () => setIsHovered(false),
    className: `${baseStyles} ${variants[variant]} ${className}`,
  };

  if (href) {
    return (
      <Link href={href} {...buttonProps}>
        {spotlight}
        {content}
      </Link>
    );
  }

  return (
    <button type={type} onClick={onClick} disabled={disabled} {...buttonProps}>
      {spotlight}
      {content}
    </button>
  );
};
