"use client";

import { Button, Spinner } from "@heroui/react";
import { ReactNode, useRef } from "react";
import gsap from "gsap";

type DynamicButtonProps = {
  children: ReactNode;
  color?:
    | "primary"
    | "secondary"
    | "success"
    | "warning"
    | "danger"
    | "default";
  size?: "sm" | "md" | "lg";
  radius?: "none" | "sm" | "md" | "lg" | "full";
  variant?:
    | "solid"
    | "bordered"
    | "flat"
    | "faded"
    | "light"
    | "ghost"
    | "shadow";
  startContent?: ReactNode;
  endContent?: ReactNode;
  fullWidth?: boolean;
  className?: string;
  onClick?: () => void;
  isDisabled?: boolean;
  isLoading?: boolean;
};

export default function DynamicButton({
  children,
  color = "primary",
  size = "md",
  radius = "md",
  variant = "solid",
  startContent,
  endContent,
  fullWidth = false,
  className = "",
  onClick,
  isDisabled = false,
  isLoading = false,
}: DynamicButtonProps) {
  const shineRef = useRef<HTMLDivElement>(null);

  const handleMouseEnter = () => {
    if (!shineRef.current || isDisabled || isLoading) return;

    gsap.killTweensOf(shineRef.current);
    gsap.fromTo(
      shineRef.current,
      { x: "-150%", opacity: 0.6 },
      { x: "150%", opacity: 0, duration: 0.8, ease: "power2.inOut" },
    );
  };

  const handleMouseLeave = () => {
    if (!shineRef.current) return;
    gsap.killTweensOf(shineRef.current);
    gsap.set(shineRef.current, { x: "-100%", opacity: 0 });
  };

  const disabledState = isDisabled || isLoading;

  return (
    <div
      className={`relative inline-block overflow-hidden rounded-${radius} ${
        fullWidth ? "w-full" : ""
      }`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div
        ref={shineRef}
        className="btn-shine pointer-events-none absolute top-0 left-0 h-full w-[40%] bg-white/40 blur-[4px] opacity-0"
      />

      <Button
        color={color}
        size={size}
        variant={variant}
        radius={radius}
        startContent={isLoading ? undefined : startContent}
        endContent={isLoading ? undefined : endContent}
        fullWidth={fullWidth}
        className={`relative z-10 flex items-center justify-center transition-all ${
          disabledState ? "opacity-70 cursor-not-allowed" : ""
        } ${className}`}
        isDisabled={disabledState}
        onPress={!disabledState ? onClick : undefined}
      >
        {isLoading ? <Spinner color="white" size="sm" /> : children}
      </Button>
    </div>
  );
}
