'use client';
import React from 'react';
import {SpellTagProps} from "@/lib/types/spell";
import {X} from 'lucide-react';
import {dynamicBg, dynamicText} from "@/lib/utils/dynamicStyles";

interface SpellTagChipProps {
    tag: SpellTagProps;
    onRemove?: () => void;
    onClick?: () => void;
    size?: 'sm' | 'md';
}

function getContrastColor(hexColor: string | null): string {
    if (!hexColor) return 'var(--color-text-primary)';
    const hex = hexColor.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? 'var(--color-darkest-background)' : 'var(--color-text-primary)';
}

export default function SpellTagChip(
    {
        tag,
        onRemove,
        onClick,
        size = 'md'
    }: SpellTagChipProps) {
    
    const chipColor: string = tag.color || 'var(--color-primary)';
    const bgClass: string = dynamicBg(chipColor);
    const textClass: string = dynamicText(getContrastColor(tag.color));

    const sizeClasses = size === 'sm'
        ? 'px-2 py-0.5 text-xs'
        : 'px-3 py-1 text-sm';

    const chipClasses = `
        inline-flex items-center gap-1.5 rounded-full font-medium
        transition-all duration-200
        ${sizeClasses}
        ${onClick ? 'cursor-pointer hover:brightness-110' : ''}
        ${bgClass} ${textClass}
    `;
    
    return (
        <span
            className={chipClasses}
            onClick={onClick}
        >
            {tag.name}
            {onRemove && (
                <button
                    onClick={(e: React.MouseEvent): void => {
                        e.stopPropagation();
                        onRemove();
                    }}
                    className="ml-0.5 hover:bg-text-primary/20 rounded-full p-0.5 transition-colors duration-200"
                >
                    <X className={size === 'sm' ? 'w-2 h-2' : 'w-2.5 h-2.5'} strokeWidth={1.75}/>
                </button>
            )}
        </span>
    );
}
