"use client"

import React, { useRef, useState } from "react"
import { motion, useMotionValue, useSpring, useTransform } from "framer-motion"
import { cn } from "../../lib/utils"

export interface CardProProps extends React.HTMLAttributes<HTMLDivElement> {
  enableGlassmorphism?: boolean
  enableParallax?: boolean
  enableTilt?: boolean
  enableGlow?: boolean
  enableReveal?: boolean
  tiltMaxAngle?: number
  glowColor?: string
  parallaxOffset?: number
}

export const CardPro = React.forwardRef<HTMLDivElement, CardProProps>(
  ({ 
    className, 
    children,
    enableGlassmorphism = true,
    enableParallax = false,
    enableTilt = true,
    enableGlow = false,
    enableReveal = false,
    tiltMaxAngle = 15,
    glowColor = "rgba(59, 130, 246, 0.5)",
    parallaxOffset = 20,
    ...props 
  }, ref) => {
    const cardRef = useRef<HTMLDivElement>(null)
    const [isHovered, setIsHovered] = useState(false)
    
    // Motion values for tilt effect
    const mouseX = useMotionValue(0)
    const mouseY = useMotionValue(0)
    
    // Spring physics for smooth animations
    const springConfig = { damping: 20, stiffness: 300 }
    const mouseXSpring = useSpring(mouseX, springConfig)
    const mouseYSpring = useSpring(mouseY, springConfig)
    
    // Transform values for 3D tilt
    const rotateX = useTransform(mouseYSpring, [-1, 1], [tiltMaxAngle, -tiltMaxAngle])
    const rotateY = useTransform(mouseXSpring, [-1, 1], [-tiltMaxAngle, tiltMaxAngle])
    
    // Glow effect position
    const glowX = useTransform(mouseXSpring, [-1, 1], [0, 100])
    const glowY = useTransform(mouseYSpring, [-1, 1], [0, 100])

    const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
      if (!cardRef.current || (!enableTilt && !enableGlow)) return
      
      const rect = cardRef.current.getBoundingClientRect()
      const centerX = rect.left + rect.width / 2
      const centerY = rect.top + rect.height / 2
      
      const x = (e.clientX - centerX) / (rect.width / 2)
      const y = (e.clientY - centerY) / (rect.height / 2)
      
      mouseX.set(x)
      mouseY.set(y)
    }

    const handleMouseEnter = () => {
      setIsHovered(true)
    }

    const handleMouseLeave = () => {
      setIsHovered(false)
      mouseX.set(0)
      mouseY.set(0)
    }

    return (
      <motion.div
        ref={cardRef || ref}
        className={cn(
          "relative rounded-xl transition-all duration-300",
          enableGlassmorphism && [
            "backdrop-blur-md",
            "bg-white/10 dark:bg-gray-900/10",
            "border border-white/20 dark:border-gray-700/20",
            "shadow-xl"
          ],
          !enableGlassmorphism && [
            "bg-card",
            "border border-border",
            "shadow-sm"
          ],
          isHovered && "shadow-2xl",
          className
        )}
        onMouseMove={handleMouseMove}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        style={{
          transformStyle: "preserve-3d",
          perspective: "1000px"
        }}
        animate={{
          rotateX: enableTilt ? rotateX.get() : 0,
          rotateY: enableTilt ? rotateY.get() : 0,
        }}
        transition={{ type: "spring", ...springConfig }}
      >
        {/* Glow effect overlay */}
        {enableGlow && (
          <motion.div
            className="absolute inset-0 rounded-xl pointer-events-none opacity-0"
            style={{
              background: `radial-gradient(600px circle at ${glowX}% ${glowY}%, ${glowColor}, transparent 40%)`,
            }}
            animate={{
              opacity: isHovered ? 1 : 0
            }}
            transition={{ duration: 0.3 }}
          />
        )}

        {/* Glassmorphism noise texture */}
        {enableGlassmorphism && (
          <div 
            className="absolute inset-0 rounded-xl opacity-[0.03] pointer-events-none"
            style={{
              backgroundImage: `url("data:image/svg+xml,%3Csvg width='100' height='100' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' /%3E%3C/filter%3E%3Crect width='100' height='100' filter='url(%23noise)' /%3E%3C/svg%3E")`,
            }}
          />
        )}

        {/* Content with parallax effect */}
        <motion.div
          className="relative z-10"
          style={{
            transform: enableParallax ? "translateZ(50px)" : undefined,
          }}
          animate={{
            x: enableParallax && isHovered ? mouseXSpring.get() * parallaxOffset : 0,
            y: enableParallax && isHovered ? mouseYSpring.get() * parallaxOffset : 0,
          }}
        >
          {children}
        </motion.div>

        {/* Reveal effect border */}
        {enableReveal && (
          <motion.div
            className="absolute inset-0 rounded-xl pointer-events-none"
            style={{
              background: `conic-gradient(from ${glowX}deg, transparent, ${glowColor}, transparent 30%)`,
              opacity: 0,
              filter: "blur(5px)",
            }}
            animate={{
              opacity: isHovered ? 0.5 : 0,
              rotate: isHovered ? 360 : 0,
            }}
            transition={{
              opacity: { duration: 0.3 },
              rotate: { duration: 20, repeat: Infinity, ease: "linear" }
            }}
          />
        )}

        {/* Soft shadow layers for depth */}
        <div className="absolute inset-0 rounded-xl -z-10">
          <motion.div
            className="absolute inset-0 rounded-xl bg-black/5 dark:bg-white/5"
            animate={{
              scale: isHovered ? 1.02 : 1,
              opacity: isHovered ? 0.5 : 0,
            }}
            transition={{ duration: 0.3 }}
            style={{ filter: "blur(10px)" }}
          />
          <motion.div
            className="absolute inset-0 rounded-xl bg-black/5 dark:bg-white/5"
            animate={{
              scale: isHovered ? 1.05 : 1,
              opacity: isHovered ? 0.3 : 0,
            }}
            transition={{ duration: 0.3 }}
            style={{ filter: "blur(20px)" }}
          />
        </div>
      </motion.div>
    )
  }
)

CardPro.displayName = "CardPro"

// Enhanced Card sub-components with animations
export const CardProHeader = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <motion.div
    ref={ref}
    className={cn("flex flex-col space-y-1.5 p-6", className)}
    initial={{ opacity: 0, y: -10 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ duration: 0.3, delay: 0.1 }}
  />
))
CardProHeader.displayName = "CardProHeader"

export const EnhancedCardTitle = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
  <motion.h3
    ref={ref}
    className={cn(
      "text-2xl font-semibold leading-none tracking-tight",
      className
    )}
    initial={{ opacity: 0, x: -10 }}
    animate={{ opacity: 1, x: 0 }}
    transition={{ duration: 0.3, delay: 0.2 }}
  />
))
EnhancedCardTitle.displayName = "EnhancedCardTitle"

export const EnhancedCardDescription = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
  <motion.p
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    initial={{ opacity: 0 }}
    animate={{ opacity: 1 }}
    transition={{ duration: 0.3, delay: 0.3 }}
  />
))
EnhancedCardDescription.displayName = "EnhancedCardDescription"

export const CardProContent = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <motion.div
    ref={ref}
    className={cn("p-6 pt-0", className)}
    initial={{ opacity: 0 }}
    animate={{ opacity: 1 }}
    transition={{ duration: 0.3, delay: 0.4 }}
  />
))
CardProContent.displayName = "CardProContent"

export const CardProFooter = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <motion.div
    ref={ref}
    className={cn("flex items-center p-6 pt-0", className)}
    initial={{ opacity: 0, y: 10 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ duration: 0.3, delay: 0.5 }}
  />
))
CardProFooter.displayName = "CardProFooter"