"use client"

import React, { useState } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Plus, X, Lock, Sparkles } from "lucide-react"
import { cn } from "../../lib/utils"
import { Card, CardContent } from "../ui/card"
import { Button } from "../ui/button"
import { useSubscription } from "../../hooks/use-subscription"

export interface FloatingActionButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  actions?: Array<{
    icon: React.ReactNode
    label: string
    onClick: () => void
  }>
  position?: "bottom-right" | "bottom-left" | "top-right" | "top-left"
  size?: "sm" | "default" | "lg"
}

const FloatingActionButtonInternal = React.forwardRef<HTMLButtonElement, FloatingActionButtonProps>(
  ({ 
    actions = [],
    position = "bottom-right", 
    size = "default",
    className,
    children,
    onClick,
    ...props 
  }, ref) => {
    const [isOpen, setIsOpen] = useState(false)

    const sizeClasses = {
      sm: "h-10 w-10",
      default: "h-12 w-12",
      lg: "h-14 w-14"
    }

    const positionClasses = {
      "bottom-right": "bottom-4 right-4",
      "bottom-left": "bottom-4 left-4",
      "top-right": "top-4 right-4",
      "top-left": "top-4 left-4"
    }

    const actionPositions = {
      "bottom-right": { x: -60, y: 0 },
      "bottom-left": { x: 60, y: 0 },
      "top-right": { x: -60, y: 0 },
      "top-left": { x: 60, y: 0 }
    }

    const handleMainClick = (e: React.MouseEvent<HTMLButtonElement>) => {
      if (actions.length > 0) {
        setIsOpen(!isOpen)
      } else if (onClick) {
        onClick(e)
      }
    }

    return (
      <div className={cn("fixed z-50", positionClasses[position])}>
        {/* Action buttons */}
        <AnimatePresence>
          {isOpen && actions.length > 0 && (
            <div className="absolute">
              {actions.map((action, index) => (
                <motion.div
                  key={index}
                  initial={{ 
                    scale: 0, 
                    opacity: 0,
                    x: 0,
                    y: 0
                  }}
                  animate={{ 
                    scale: 1, 
                    opacity: 1,
                    x: actionPositions[position].x,
                    y: actionPositions[position].y * (index + 1) - 10
                  }}
                  exit={{ 
                    scale: 0, 
                    opacity: 0,
                    x: 0,
                    y: 0
                  }}
                  transition={{ 
                    delay: index * 0.05,
                    type: "spring",
                    stiffness: 200,
                    damping: 15
                  }}
                  className="absolute flex items-center gap-2"
                  style={{
                    transform: `translate(${position.includes('right') ? '0' : '0'}, ${position.includes('bottom') ? '0' : '0'})`
                  }}
                >
                  {/* Label */}
                  <motion.div
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.8 }}
                    transition={{ delay: (index + 1) * 0.05 }}
                    className={cn(
                      "px-2 py-1 bg-background/90 backdrop-blur-sm text-sm font-medium rounded-md shadow-sm border whitespace-nowrap",
                      position.includes('right') ? 'mr-2' : 'ml-2'
                    )}
                  >
                    {action.label}
                  </motion.div>
                  
                  {/* Action button */}
                  <button
                    onClick={() => {
                      action.onClick()
                      setIsOpen(false)
                    }}
                    className={cn(
                      "inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
                      sizeClasses[size]
                    )}
                  >
                    {action.icon}
                  </button>
                </motion.div>
              ))}
            </div>
          )}
        </AnimatePresence>

        {/* Main FAB */}
        <motion.button
          ref={ref}
          className={cn(
            "inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
            sizeClasses[size],
            className
          )}
          onClick={handleMainClick}
          whileHover={{ scale: 1.1 }}
          whileTap={{ scale: 0.9 }}
          animate={{ rotate: isOpen ? 45 : 0 }}
          transition={{ duration: 0.2 }}
        >
          {children || (actions.length > 0 ? <Plus className="h-5 w-5" /> : <Plus className="h-5 w-5" />)}
        </motion.button>

        {/* Backdrop */}
        <AnimatePresence>
          {isOpen && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 z-[-1]"
              onClick={() => setIsOpen(false)}
            />
          )}
        </AnimatePresence>
      </div>
    )
  }
)

FloatingActionButtonInternal.displayName = "FloatingActionButtonInternal"

export const FloatingActionButton = React.forwardRef<HTMLButtonElement, FloatingActionButtonProps>(
  ({ className, ...props }, ref) => {
    // Check if we're in docs mode or have pro access
    const { hasProAccess, isLoading } = useSubscription()
    
    // In docs mode, always show the component
    
    // If not in docs mode and no pro access, show upgrade prompt
    if (!isLoading && !hasProAccess) {
      return (
        <Card className={cn("w-fit", 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">
                  Floating Action 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 <FloatingActionButtonInternal className={className} ref={ref} {...props} />
  }
)

FloatingActionButton.displayName = "FloatingActionButton"