import { cva, type VariantProps } from 'class-variance-authority'
import { motion } from 'framer-motion'
import { FC, ReactNode } from 'react'

const tagVariants = cva(
    'inline-flex items-center justify-center rounded-full px-3 py-1 text-sm font-medium transition-all',
    {
        variants: {
            variant: {
                default: 'bg-gray-100 text-gray-800 hover:bg-gray-200',
                primary: 'bg-blue-100 text-blue-800 hover:bg-blue-200',
                success: 'bg-green-100 text-green-800 hover:bg-green-200',
                warning: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-200',
                danger: 'bg-red-100 text-red-800 hover:bg-red-200',
            },
            size: {
                sm: 'text-xs px-2 py-0.5',
                md: 'text-sm px-3 py-1',
                lg: 'text-base px-4 py-1.5',
            },
            interactive: {
                true: 'cursor-pointer',
            },
            removable: {
                true: 'pr-2',
            },
        },
        defaultVariants: {
            variant: 'default',
            size: 'md',
            interactive: false,
            removable: false,
        },
    }
)

interface TagProps extends VariantProps<typeof tagVariants> {
    children: ReactNode
    onClick?: () => void
    onRemove?: () => void
    className?: string
}

const Tag: FC<TagProps> = ({
    children,
    variant,
    size,
    interactive,
    removable,
    onClick,
    onRemove,
    className,
}) => {
    return (
        <motion.span
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            whileHover={interactive ? { scale: 1.05 } : undefined}
            whileTap={interactive ? { scale: 0.95 } : undefined}
            className={tagVariants({ variant, size, interactive, removable, className })}
            onClick={onClick}
        >
            {children}
            {removable && (
                <motion.button
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                    onClick={(e) => {
                        e.stopPropagation()
                        onRemove?.()
                    }}
                    className="ml-1.5 rounded-full p-0.5 hover:bg-black/5"
                >
                    <svg
                        className="h-3 w-3 opacity-50"
                        viewBox="0 0 12 12"
                        fill="currentColor"
                    >
                        <path d="M6 4.586l2.293-2.293a1 1 0 0 1 1.414 1.414L7.414 6l2.293 2.293a1 1 0 0 1-1.414 1.414L6 7.414l-2.293 2.293a1 1 0 1 1-1.414-1.414L4.586 6 2.293 3.707a1 1 0 0 1 1.414-1.414L6 4.586z" />
                    </svg>
                </motion.button>
            )}
        </motion.span>
    )
}

export default Tag