"use client"

import React, { useState } from "react"
import { motion } from "framer-motion"
import { Loader2, Check, X, Lock, Sparkles } from "lucide-react"
import { cn } from "../../lib/utils"
import { cva, type VariantProps } from "class-variance-authority"
import { Card, CardContent } from "../ui/card"
import { Button } from "../ui/button"
import { useSubscription } from "../../hooks/use-subscription"

const moonUIAnimatedButtonProVariants = cva(
  "relative inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 overflow-hidden min-w-fit",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
        gradient: "bg-gradient-to-r from-purple-600 to-pink-600 text-white hover:from-purple-700 hover:to-pink-700",
        glow: "bg-primary text-primary-foreground shadow-lg hover:shadow-xl hover:shadow-primary/25",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        xl: "h-11 rounded-md px-6 text-base font-medium",
        icon: "h-9 w-9",
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    },
  }
)

interface MoonUIAnimatedButtonProProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof moonUIAnimatedButtonProVariants> {
  state?: "idle" | "loading" | "success" | "error"
  onStateChange?: (state: "idle" | "loading" | "success" | "error") => void
  loadingText?: string
  successText?: string
  errorText?: string
  ripple?: boolean
  iconRotate?: boolean
  shimmerSpeed?: "slow" | "normal" | "fast"
  glowIntensity?: "low" | "medium" | "high"
  showProgressBar?: boolean
  autoResetDelay?: number
  animation?: "none" | "bounce" | "pulse" | "shimmer" | "slide" | "scale" | "rotate" | "shake"
}

const MoonUIAnimatedButtonProInternal = React.forwardRef<HTMLButtonElement, MoonUIAnimatedButtonProProps>(
  ({ 
    className, 
    variant, 
    size, 
    animation = "none",
    state = "idle", 
    onStateChange, 
    children, 
    onClick, 
    loadingText = "Loading...",
    successText = "Success!",
    errorText = "Error!",
    ripple = false,
    iconRotate = false,
    shimmerSpeed = "normal",
    glowIntensity = "medium",
    showProgressBar = false,
    autoResetDelay = 2000,
    onDrag,
    onDragEnd,
    onDragStart,
    onAnimationStart,
    onAnimationEnd,
    ...props 
  }, ref) => {
    const [internalState, setInternalState] = useState<"idle" | "loading" | "success" | "error">("idle")
    const [ripples, setRipples] = useState<Array<{x: number, y: number, id: number}>>([])
    const [progress, setProgress] = useState(0)
    const [isHovered, setIsHovered] = useState(false)
    const currentState = state !== "idle" ? state : internalState

    const handleClick = async (e: React.MouseEvent<HTMLButtonElement>) => {
      if (currentState === "loading") return

      // Ripple effect
      if (ripple) {
        const rect = e.currentTarget.getBoundingClientRect()
        const x = e.clientX - rect.left
        const y = e.clientY - rect.top
        const id = Date.now()
        
        setRipples([...ripples, { x, y, id }])
        setTimeout(() => {
          setRipples(prev => prev.filter(r => r.id !== id))
        }, 600)
      }

      setInternalState("loading")
      onStateChange?.("loading")
      setProgress(0)

      // Simulate progress
      if (showProgressBar) {
        const progressInterval = setInterval(() => {
          setProgress(prev => {
            if (prev >= 90) {
              clearInterval(progressInterval)
              return 90
            }
            return prev + 10
          })
        }, 200)
      }

      if (onClick) {
        try {
          await onClick(e)
          setProgress(100)
          setInternalState("success")
          onStateChange?.("success")
          
          setTimeout(() => {
            setInternalState("idle")
            onStateChange?.("idle")
            setProgress(0)
          }, autoResetDelay)
        } catch (error) {
          setProgress(0)
          setInternalState("error")
          onStateChange?.("error")
          
          setTimeout(() => {
            setInternalState("idle")
            onStateChange?.("idle")
          }, autoResetDelay)
        }
      }
    }

    const getIcon = () => {
      const iconClass = cn("h-4 w-4", {
        "animate-spin": currentState === "loading" || (iconRotate && currentState !== "idle"),
      })
      
      switch (currentState) {
        case "loading":
          return <Loader2 className={iconClass} />
        case "success":
          return <Check className={cn(iconClass, "animate-scale-in")} />
        case "error":
          return <X className={cn(iconClass, "animate-shake")} />
        default:
          return null
      }
    }

    const getBackgroundColor = () => {
      switch (currentState) {
        case "success":
          return "bg-green-600"
        case "error":
          return "bg-red-600"
        default:
          return ""
      }
    }

    const getShimmerSpeed = () => {
      switch (shimmerSpeed) {
        case "slow":
          return "duration-1500"
        case "fast":
          return "duration-500"
        default:
          return "duration-1000"
      }
    }

    const getGlowIntensity = () => {
      switch (glowIntensity) {
        case "low":
          return "shadow-lg"
        case "high":
          return "shadow-2xl"
        default:
          return "shadow-xl"
      }
    }


    // whileHover direkt olarak kullanılacak
    let whileHoverAnimation: any = undefined
    let whileTapAnimation: any = undefined

    // Animation specific hover states
    if (animation === "bounce") {
      whileHoverAnimation = { 
        y: [0, -10, 0],
        transition: { 
          duration: 0.6,
          repeat: Infinity,
          repeatType: "loop" 
        }
      }
    } else if (animation === "pulse") {
      whileHoverAnimation = { 
        scale: [1, 1.1, 1],
        transition: { 
          duration: 1,
          repeat: Infinity,
          repeatType: "loop"
        }
      }
    } else if (animation === "shake") {
      // Shake için CSS animation kullanacağız
      whileHoverAnimation = undefined
    } else if (animation === "rotate") {
      whileHoverAnimation = { 
        rotate: 10,
        transition: { type: "spring", stiffness: 300 }
      }
    } else if (animation === "scale") {
      whileHoverAnimation = { scale: 1.05 }
      whileTapAnimation = { scale: 0.95 }
    } else if (animation === "slide") {
      whileHoverAnimation = { y: -4 }
    }

    return (
      <motion.button
        {...props}
        className={cn(
          moonUIAnimatedButtonProVariants({ variant, size }), 
          variant === "glow" && getGlowIntensity(),
          animation === "shake" && isHovered && "animate-shake",
          className
        )}
        ref={ref}
        onClick={handleClick}
        disabled={currentState === "loading" || props.disabled}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        whileHover={whileHoverAnimation}
        whileTap={whileTapAnimation}
      >
        {/* Progress Bar */}
        {showProgressBar && currentState === "loading" && (
          <motion.div
            className="absolute bottom-0 left-0 h-1 bg-primary-foreground/20 rounded-full"
            initial={{ width: 0 }}
            animate={{ width: `${progress}%` }}
            transition={{ duration: 0.3 }}
          />
        )}

        {/* Shimmer Effect */}
        {animation === "shimmer" && (
          <motion.div 
            className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent"
            initial={{ x: "-100%" }}
            animate={{ x: "100%" }}
            transition={{ 
              duration: shimmerSpeed === "slow" ? 1.5 : shimmerSpeed === "fast" ? 0.5 : 1,
              repeat: Infinity,
              repeatDelay: 1
            }}
          />
        )}

        {/* Content */}
        <div className="relative flex items-center justify-center gap-2 z-10">
          {/* Icon variant için özel düzenleme */}
          {size === "icon" ? (
            // Icon size için sadece icon göster
            currentState === "idle" ? (
              children
            ) : (
              getIcon()
            )
          ) : (
            // Diğer boyutlar için normal akış
            <>
              {currentState === "idle" ? (
                <>
                  {React.isValidElement(children) && React.cloneElement(children as React.ReactElement)}
                  {typeof children === 'string' && children}
                  {React.isValidElement(children) || typeof children === 'string' ? null : children}
                </>
              ) : (
                <>
                  {getIcon()}
                  <span className="ml-2">
                    {currentState === "loading" && loadingText}
                    {currentState === "success" && successText}
                    {currentState === "error" && errorText}
                  </span>
                </>
              )}
            </>
          )}
        </div>

        {/* Background animation */}
        <motion.div
          className={cn(
            "absolute inset-0 rounded-md",
            getBackgroundColor()
          )}
          initial={{ scale: 0, opacity: 0 }}
          animate={{
            scale: currentState === "success" || currentState === "error" ? 1 : 0,
            opacity: currentState === "success" || currentState === "error" ? 0.2 : 0
          }}
          transition={{ duration: 0.3 }}
          style={{ zIndex: 0 }}
        />

        {/* Ripple Effect */}
        {ripples.map(ripple => (
          <span
            key={ripple.id}
            className="absolute bg-primary/20 rounded-full animate-ripple pointer-events-none"
            style={{
              left: ripple.x - 10,
              top: ripple.y - 10,
              width: 20,
              height: 20,
            }}
          />
        ))}
      </motion.button>
    )
  }
)

MoonUIAnimatedButtonProInternal.displayName = "MoonUIAnimatedButtonProInternal"

export const MoonUIAnimatedButtonPro = React.forwardRef<HTMLButtonElement, MoonUIAnimatedButtonProProps>(
  (props, ref) => {
    // Pro package - always show component
    const { hasProAccess, isLoading } = useSubscription()
    
    // Show upgrade prompt if no pro access
    if (!isLoading && !hasProAccess) {
      return (
        <Card className={cn("w-fit", props.className)}>
          <CardContent className="py-6 text-center">
            <div className="space-y-4">
              <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
                <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
              </div>
              <div>
                <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
                <p className="text-muted-foreground text-xs mb-4">
                  Animated Button is available exclusively to MoonUI Pro subscribers.
                </p>
                <a href="/pricing">
                  <Button size="sm">
                    <Sparkles className="mr-2 h-4 w-4" />
                    Upgrade to Pro
                  </Button>
                </a>
              </div>
            </div>
          </CardContent>
        </Card>
      )
    }

    return <MoonUIAnimatedButtonProInternal {...props} ref={ref} />
  }
)

MoonUIAnimatedButtonPro.displayName = "MoonUIAnimatedButtonPro"

export { moonUIAnimatedButtonProVariants }
export type { MoonUIAnimatedButtonProProps }