'use client';

import React, { useState } from 'react';
import { Tag, Input, Space } from 'antd';
import { Plus } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import type { FormItemProps } from 'antd';

interface TagInputProps extends Omit<FormItemProps, 'children'> {
    value?: string[];
    onChange?: (tags: string[]) => void;
    placeholder?: string;
    maxTags?: number;
    colors?: string[];
}

export function TagInput({
    value = [],
    onChange,
    placeholder = 'Digite e pressione Enter',
    maxTags = 10,
    colors = [
        'magenta',
        'red',
        'volcano',
        'orange',
        'gold',
        'lime',
        'green',
        'cyan',
        'blue',
        'geekblue',
        'purple',
    ],
}: TagInputProps) {
    const [inputValue, setInputValue] = React.useState('');

    const handleInputConfirm = () => {
        if (inputValue && value.length < maxTags && !value.includes(inputValue.trim())) {
            onChange?.([...value, inputValue.trim()]);
            setInputValue('');
        }
    };

    const handleTagClose = (removedTag: string) => {
        onChange?.(value.filter((tag) => tag !== removedTag));
    };

    const getTagColor = (index: number) => {
        return colors[index % colors.length];
    };

    return (
        <div>
            <Space size={[0, 8]} wrap style={{ marginBottom: 8 }}>
                {value.map((tag, index) => (
                    <Tag
                        key={tag}
                        closable
                        color={getTagColor(index)}
                        onClose={() => handleTagClose(tag)}
                    >
                        {tag}
                    </Tag>
                ))}
            </Space>
            {value.length < maxTags && (
                <Input
                    type="text"
                    size="small"
                    style={{ width: 150 }}
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                    placeholder={placeholder}
                    prefix={<Plus size={ICON_SIZE_MD} aria-hidden />}
                />
            )}
        </div>
    );
}
