"use client"

import React, { ReactNode } from "react"
import { motion, useMotionValue, useTransform, animate, PanInfo } from "framer-motion"
import { cn } from "../../lib/utils"

interface SwipeableCardProps {
  children: ReactNode
  onSwipeLeft?: () => void
  onSwipeRight?: () => void
  onSwipeStart?: () => void
  onSwipeEnd?: () => void
  threshold?: number
  disabled?: boolean
  className?: string
  style?: React.CSSProperties
}

export const SwipeableCard = React.forwardRef<HTMLDivElement, SwipeableCardProps>(
  ({
    children,
    onSwipeLeft,
    onSwipeRight,
    onSwipeStart,
    onSwipeEnd,
    threshold = 100,
    disabled = false,
    className,
    style,
    ...props
  }, ref) => {
    const x = useMotionValue(0)
    const rotate = useTransform(x, [-200, 200], [-30, 30])
    const likeOpacity = useTransform(x, [0, threshold], [0, 1])
    const nopeOpacity = useTransform(x, [-threshold, 0], [1, 0])

    const handleDragStart = () => {
      if (disabled) return
      onSwipeStart?.()
    }

    const handleDragEnd = (event: any, info: PanInfo) => {
      if (disabled) return
      
      onSwipeEnd?.()
      
      if (Math.abs(info.offset.x) > threshold) {
        const direction = info.offset.x > 0 ? "right" : "left"
        const exitX = info.offset.x > 0 ? 400 : -400
        
        animate(x, exitX, { duration: 0.3 })
        
        if (direction === "right" && onSwipeRight) {
          onSwipeRight()
        } else if (direction === "left" && onSwipeLeft) {
          onSwipeLeft()
        }
      } else {
        animate(x, 0, { type: "spring", stiffness: 300, damping: 20 })
      }
    }

    return (
      <motion.div
        ref={ref}
        drag={disabled ? false : "x"}
        dragConstraints={{ left: -300, right: 300 }}
        style={{ x, rotate, ...style }}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        className={cn(
          "relative cursor-grab active:cursor-grabbing select-none",
          disabled && "cursor-default",
          className
        )}
        {...props}
      >
        {/* Like indicator */}
        <motion.div
          style={{ opacity: likeOpacity }}
          className="absolute top-4 right-4 bg-green-500 text-white px-3 py-1 rounded-lg font-bold text-lg rotate-[15deg] pointer-events-none z-10"
        >
          LIKE
        </motion.div>
        
        {/* Nope indicator */}
        <motion.div
          style={{ opacity: nopeOpacity }}
          className="absolute top-4 left-4 bg-red-500 text-white px-3 py-1 rounded-lg font-bold text-lg rotate-[-15deg] pointer-events-none z-10"
        >
          NOPE
        </motion.div>
        
        {children}
      </motion.div>
    )
  }
)

SwipeableCard.displayName = "SwipeableCard"