import { useState, type KeyboardEvent } from 'react'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'

export function TagInput({
  value,
  onChange,
  placeholder = '输入标签后回车',
  className,
}: {
  value?: string
  onChange: (v: string) => void
  placeholder?: string
  className?: string
}) {
  const [draft, setDraft] = useState('')
  const tags = (value || '')
    .split(',')
    .map((t) => t.trim())
    .filter(Boolean)

  function commit(next: string[]) {
    onChange(next.join(','))
  }

  function addTag(raw: string) {
    const t = raw.trim()
    if (!t || tags.includes(t)) {
      setDraft('')
      return
    }
    commit([...tags, t])
    setDraft('')
  }

  function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault()
      addTag(draft)
    } else if (e.key === 'Backspace' && !draft && tags.length) {
      commit(tags.slice(0, -1))
    }
  }

  return (
    <div className={cn('ui-control flex min-h-9 flex-wrap items-center gap-1.5 px-2 py-1', className)}>
      {tags.map((tag) => (
        <span
          key={tag}
          className="inline-flex items-center gap-1 rounded bg-[var(--bg-selected)] px-1.5 py-0.5 text-xs text-[var(--text-primary)]"
        >
          {tag}
          <button type="button" className="opacity-70 hover:opacity-100" onClick={() => commit(tags.filter((t) => t !== tag))}>
            <X size={12} />
          </button>
        </span>
      ))}
      <input
        className="min-w-[120px] flex-1 bg-transparent text-sm outline-none placeholder:text-[var(--text-muted)]"
        value={draft}
        placeholder={tags.length ? '' : placeholder}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={onKeyDown}
        onBlur={() => draft && addTag(draft)}
      />
    </div>
  )
}
