import { useState, KeyboardEvent } from "react";

interface TagInputProps {
    label?: string;
    placeholder?: string;
    value: string[];
    onChange: (tags: string[]) => void;
}

const TagInput = ({
    label,
    placeholder = "Type and press Enter...",
    value,
    onChange,
}: TagInputProps) => {
    const [input, setInput] = useState("");

    const addTag = (tag: string) => {
        const trimmed = tag.trim();
        if (trimmed && !value.includes(trimmed)) {
            onChange([...value, trimmed]);
        }
    };

    const removeTag = (index: number) => {
        onChange(value.filter((_, i) => i !== index));
    };

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter" || e.key === ",") {
            e.preventDefault();
            addTag(input);
            setInput("");
        }

        // 🔥 Bonus: backspace deletes last tag
        if (e.key === "Backspace" && !input && value.length > 0) {
            removeTag(value.length - 1);
        }
    };

    return (
        <div>
            <div className="flex flex-wrap items-center gap-2 border rounded-lg px-3 py-2 focus-within:border-red-400">

                {value.map((tag, index) => (
                    <span
                        key={index}
                        className="flex items-center gap-1 bg-rose-100 text-rose-600 px-2 py-1 rounded-md text-xs"
                    >
                        {tag}
                        <button
                            type="button"
                            onClick={() => removeTag(index)}
                            className="text-rose-500 hover:text-rose-700"
                        >
                            ✕
                        </button>
                    </span>
                ))}

                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder={placeholder}
                    className="flex-1 min-w-[120px] outline-none text-sm"
                />
            </div>
        </div>
    );
};

export default TagInput;
