import { type FC } from 'react'
import { CloseCircle } from 'iconsax-react'
import Input from '../../../components/Input'
import { useTagManager } from '../hooks/useTagManager'

interface TagManagerProps {
    tags: string[]
    onTagsChange: (tags: string[]) => void
}

export const TagManager: FC<TagManagerProps> = ({ tags, onTagsChange }) => {
    const { tagInput, setTagInput, removeTag } = useTagManager(tags)

    const handleAddTag = () => {
        const trimmedTag = tagInput.trim()
        if (trimmedTag && !tags.includes(trimmedTag)) {
            onTagsChange([...tags, trimmedTag])
            setTagInput('')
        }
    }

    const handleRemoveTag = (tagToRemove: string) => {
        removeTag(tagToRemove)
        onTagsChange(tags.filter(tag => tag !== tagToRemove))
    }

    const handleKeyDownWithUpdate = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            e.preventDefault()
            handleAddTag()
        }
    }

    return (
        <div>
            <label className="block text-sm font-medium mb-2">برچسب‌ها</label>
            <div className="flex flex-wrap gap-2 mb-2">
                {tags.map((tag, index) => (
                    <span
                        key={index}
                        className="inline-flex items-center gap-2 bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm"
                    >
                        {tag}
                        <button
                            type="button"
                            onClick={() => handleRemoveTag(tag)}
                            className="text-blue-600 hover:text-blue-800"
                        >
                            <CloseCircle color='red' size={16} />
                        </button>
                    </span>
                ))}
            </div>
            <Input
                placeholder='برچسب را تایپ کنید و Enter بزنید...'
                value={tagInput}
                onChange={(e) => setTagInput(e.target.value)}
                onKeyDown={handleKeyDownWithUpdate}
            />
        </div>
    )
}
