/**
 * Tag Search Selector Component
 *
 * Searchable tag selector with type-ahead filtering.
 * Shows selected tags as pills, with a search input to find and add more.
 */

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

interface TagItem {
  id: number
  name: string
  slug?: string
  color: string
  description?: string | null
}

interface TagSearchSelectorProps {
  tags: TagItem[]
  selectedTagIds: number[]
  onChange: (tagIds: number[]) => void
  placeholder?: string
  label?: string
  compact?: boolean
}

export default function TagSearchSelector({
  tags,
  selectedTagIds,
  onChange,
  placeholder = 'Search tags...',
  label,
  compact = false,
}: TagSearchSelectorProps) {
  const [search, setSearch] = useState('')
  const [isOpen, setIsOpen] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  const selectedTags = tags.filter(t => selectedTagIds.includes(t.id))
  const filteredTags = tags.filter(
    t => !selectedTagIds.includes(t.id) &&
      t.name.toLowerCase().includes(search.toLowerCase())
  )

  const addTag = (tagId: number) => {
    onChange([...selectedTagIds, tagId])
    setSearch('')
    inputRef.current?.focus()
  }

  const removeTag = (tagId: number) => {
    onChange(selectedTagIds.filter(id => id !== tagId))
  }

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false)
      }
    }
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen])

  const pillSize = compact ? 'px-2 py-0.5 text-xs' : 'px-2.5 py-1 text-sm'
  const removeSize = compact ? 'w-3 h-3' : 'w-3.5 h-3.5'

  return (
    <div ref={containerRef} className="relative">
      {label && (
        <label className={`flex items-center gap-2 ${compact ? 'text-xs text-muted-foreground mb-1' : 'text-sm font-medium mb-2'}`}>
          <Tag className="w-4 h-4" />
          {label}
        </label>
      )}

      {/* Selected tags + search input */}
      <div
        className={`flex flex-wrap gap-1.5 items-center min-h-[38px] px-3 py-1.5 rounded-lg border bg-background transition-colors cursor-text ${
          isOpen ? 'border-primary ring-2 ring-primary/20' : 'border-border hover:border-primary/50'
        }`}
        onClick={() => {
          setIsOpen(true)
          inputRef.current?.focus()
        }}
      >
        {selectedTags.map(tag => (
          <span
            key={tag.id}
            className={`inline-flex items-center gap-1 ${pillSize} rounded-full text-white font-medium`}
            style={{ backgroundColor: tag.color }}
          >
            {tag.name}
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation()
                removeTag(tag.id)
              }}
              className="hover:bg-white/20 rounded-full p-0.5"
            >
              <X className={removeSize} />
            </button>
          </span>
        ))}
        <input
          ref={inputRef}
          type="text"
          value={search}
          onChange={(e) => {
            setSearch(e.target.value)
            setIsOpen(true)
          }}
          onFocus={() => setIsOpen(true)}
          onKeyDown={(e) => {
            if (e.key === 'Backspace' && !search && selectedTagIds.length > 0) {
              removeTag(selectedTagIds[selectedTagIds.length - 1])
            }
            if (e.key === 'Escape') {
              setIsOpen(false)
              inputRef.current?.blur()
            }
            if (e.key === 'Enter' && filteredTags.length > 0) {
              e.preventDefault()
              addTag(filteredTags[0].id)
            }
          }}
          placeholder={selectedTags.length === 0 ? placeholder : ''}
          className="flex-1 min-w-[80px] bg-transparent outline-none text-sm placeholder:text-muted-foreground"
        />
        {selectedTags.length === 0 && !search && (
          <Search className="w-4 h-4 text-muted-foreground flex-shrink-0" />
        )}
      </div>

      {/* Dropdown */}
      {isOpen && filteredTags.length > 0 && (
        <div className="absolute z-50 mt-1 w-full bg-popover rounded-lg shadow-lg border border-border overflow-hidden">
          <div className="max-h-48 overflow-y-auto">
            {filteredTags.map(tag => (
              <button
                key={tag.id}
                type="button"
                onClick={() => addTag(tag.id)}
                className="w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-secondary transition-colors text-sm"
              >
                <span
                  className="w-3 h-3 rounded-full flex-shrink-0"
                  style={{ backgroundColor: tag.color }}
                />
                <span>{tag.name}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {isOpen && search && filteredTags.length === 0 && (
        <div className="absolute z-50 mt-1 w-full bg-popover rounded-lg shadow-lg border border-border overflow-hidden">
          <div className="px-3 py-3 text-sm text-muted-foreground text-center">
            No matching tags
          </div>
        </div>
      )}
    </div>
  )
}
