"use client"

import * as React from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { Loader2, Check } from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants, rippleVariants } from "@/lib/animations"

const animatedButtonVariants = cva(
  "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 relative overflow-hidden",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground hover:bg-primary/90",
        destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
        outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default: "h-10 px-4 py-2",
        sm: "h-9 rounded-md px-3",
        lg: "h-11 rounded-md px-8",
        icon: "h-10 w-10",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

interface RippleProps {
  x: number
  y: number
  size: number
}

const Ripple: React.FC<RippleProps> = ({ x, y, size }) => (
  <motion.span
    className="absolute rounded-full bg-white/30 pointer-events-none"
    style={{
      left: x - size / 2,
      top: y - size / 2,
      width: size,
      height: size,
    }}
    variants={rippleVariants}
    initial="initial"
    animate="animate"
  />
)

export interface AnimatedButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof animatedButtonVariants> {
  asChild?: boolean
  loading?: boolean
  success?: boolean
  loadingText?: string
  successText?: string
  enableRipple?: boolean
}

const AnimatedButton = React.forwardRef<HTMLButtonElement, AnimatedButtonProps>(
  (
    {
      className,
      variant,
      size,
      asChild = false,
      loading = false,
      success = false,
      loadingText,
      successText,
      enableRipple = true,
      children,
      onClick,
      ...props
    },
    ref
  ) => {
    const [ripples, setRipples] = React.useState<RippleProps[]>([])
    const buttonRef = React.useRef<HTMLButtonElement>(null)

    React.useImperativeHandle(ref, () => buttonRef.current!)

    const createRipple = (event: React.MouseEvent<HTMLButtonElement>) => {
      if (!enableRipple || loading || success) return

      const button = buttonRef.current
      if (!button) return

      const rect = button.getBoundingClientRect()
      const size = Math.max(rect.width, rect.height)
      const x = event.clientX - rect.left
      const y = event.clientY - rect.top

      const newRipple: RippleProps = {
        x,
        y,
        size,
      }

      setRipples((prev) => [...prev, newRipple])

      // Remove ripple after animation
      setTimeout(() => {
        setRipples((prev) => prev.slice(1))
      }, 600)
    }

    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
      createRipple(event)
      onClick?.(event)
    }

    const buttonContent = () => {
      if (success) {
        return (
          <motion.div
            className="flex items-center gap-2"
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ type: "spring", stiffness: 300, damping: 20 }}
          >
            <Check className="h-4 w-4" />
            {successText || "Success!"}
          </motion.div>
        )
      }

      if (loading) {
        return (
          <motion.div
            className="flex items-center gap-2"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.2 }}
          >
            <Loader2 className="h-4 w-4 animate-spin" />
            {loadingText || "Loading..."}
          </motion.div>
        )
      }

      return children
    }

    if (asChild) {
      return (
        <Slot
          className={cn(animatedButtonVariants({ variant, size, className }))}
          ref={buttonRef}
          onClick={handleClick}
          disabled={loading || success}
          {...props}
        >
          {buttonContent()}
          <AnimatePresence>
            {ripples.map((ripple, index) => (
              <Ripple key={index} {...ripple} />
            ))}
          </AnimatePresence>
        </Slot>
      )
    }

    return (
      <motion.button
        className={cn(animatedButtonVariants({ variant, size, className }))}
        ref={buttonRef}
        onClick={handleClick}
        disabled={loading || success}
        variants={buttonVariants}
        initial="initial"
        whileHover="hover"
        whileTap="tap"
        animate={loading ? "loading" : "initial"}
        {...(props as any)}
      >
        {buttonContent()}
        <AnimatePresence>
          {ripples.map((ripple, index) => (
            <Ripple key={index} {...ripple} />
          ))}
        </AnimatePresence>
      </motion.button>
    )
  }
)

AnimatedButton.displayName = "AnimatedButton"

export { AnimatedButton, animatedButtonVariants }
