import { useState, useRef } from 'react'
import { X } from 'lucide-react'

const TAG_COLORS = [
  'bg-indigo-500/20 border-indigo-500/40 text-indigo-300',
  'bg-violet-500/20 border-violet-500/40 text-violet-300',
  'bg-sky-500/20 border-sky-500/40 text-sky-300',
  'bg-emerald-500/20 border-emerald-500/40 text-emerald-300',
  'bg-amber-500/20 border-amber-500/40 text-amber-300',
  'bg-rose-500/20 border-rose-500/40 text-rose-300',
  'bg-teal-500/20 border-teal-500/40 text-teal-300',
  'bg-pink-500/20 border-pink-500/40 text-pink-300',
]

export function tagColor(tag) {
  let hash = 0
  for (let i = 0; i < tag.length; i++) hash = (hash * 31 + tag.charCodeAt(i)) >>> 0
  return TAG_COLORS[hash % TAG_COLORS.length]
}

export default function TagInput({ tags = [], onChange }) {
  const [input, setInput] = useState('')
  const inputRef = useRef(null)

  const addTag = (raw) => {
    const tag = raw.trim().toLowerCase().replace(/\s+/g, '-')
    if (!tag || tags.includes(tag)) return
    onChange([...tags, tag])
    setInput('')
  }

  const removeTag = (tag) => onChange(tags.filter(t => t !== tag))

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault()
      addTag(input)
    } else if (e.key === 'Backspace' && !input && tags.length) {
      removeTag(tags[tags.length - 1])
    }
  }

  return (
    <div
      className="flex flex-wrap gap-1.5 px-2.5 py-2 rounded-lg bg-gray-800 border border-gray-700 focus-within:border-indigo-500 transition-colors cursor-text min-h-[40px]"
      onClick={() => inputRef.current?.focus()}
    >
      {tags.map(tag => (
        <span
          key={tag}
          className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${tagColor(tag)}`}
        >
          {tag}
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); removeTag(tag) }}
            className="opacity-60 hover:opacity-100 transition-opacity"
          >
            <X size={10} />
          </button>
        </span>
      ))}
      <input
        ref={inputRef}
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder={tags.length === 0 ? 'Ajouter un tag…' : ''}
        className="flex-1 min-w-[120px] bg-transparent text-sm outline-none placeholder-gray-600"
      />
    </div>
  )
}
