"use client";
import React, { useRef, useEffect } from "react";
import { ArrowRight, ArrowUpRight } from "lucide-react";
import { Button } from "./ui/button";
import { gsap } from "gsap";
import { cn } from "@/lib/utils";

// Custom animated button component
const CustomButton = ({ text, className }) => {
  // Refs to target the button and the arrow icon for GSAP
  const buttonRef = useRef(null);
  const arrowRef = useRef(null);

  // Use a state variable to handle the hover state
  const [isHovered, setIsHovered] = React.useState(false);

  useEffect(() => {
    if (typeof gsap === "undefined") {
      console.error("GSAP is not available");
      return;
    }

    // Check if the DOM elements are available
    if (!buttonRef.current || !arrowRef.current) return;

    // Use GSAP to animate the background color and the arrow icon
    gsap.to(buttonRef.current, {
      backgroundColor: isHovered ? "#000000" : "#22d3ee", // black on hover, yellow otherwise
      ease: "power2.out",
      duration: 0.3,
      overwrite: "auto",
    });

    gsap.to(arrowRef.current, {
      backgroundColor: isHovered ? "#404040" : "#0891b2", // cyan on hover, black otherwise
      color: isHovered ? "#fff" : "#fff", // black on hover, yellow otherwise
      x: isHovered ? 0 : 0, // Move arrow to the right on hover, back to original position on mouse leave
      rotate: isHovered ? "45deg" : "0deg", // Spin the arrow
      ease: "power2.out",
      duration: 0.6,
      overwrite: "auto",
    });
  }, [isHovered]); // Rerun the effect whenever the hover state changes

  return (
    <Button
      ref={buttonRef}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      className={cn(
        "bg-cyan-400 font-poppins text-foreground hover:text-background rounded-full px-1 py-7 text-lg font-medium shadow-lg hover:shadow-xl transition-shadow",
        className
      )}
    >
      <span className="flex items-center space-x-2 gap-2 pl-4 px-2">
        {text}
        <ArrowUpRight
          ref={arrowRef}
          className="ml-2 size-10 rounded-full p-1 text-white bg-cyan-600"
        />
      </span>
    </Button>
  );
};

export default CustomButton;
