'use client'

import { useState, useRef, useEffect, useId } from'react'
import { ChevronDown, X, Search } from'lucide-react'
import { nextHighlightIndex } from'@/lib/ui/list-keyboard-nav'

interface Item { id: string; label: string; sublabel?: string }

interface Props {
 label: string
 placeholder?: string
 items: Item[]
 selectedIds: string[]
 onChange: (ids: string[]) => void
 disabled?: boolean
}

export function enterToggleIndex(highlighted: number, count: number): number | null {
 return highlighted >= 0 && highlighted < count ? highlighted : null
}

export default function MultiSelectField({
 label,
 placeholder ='Auswählen…',
 items,
 selectedIds,
 onChange,
 disabled = false,
}: Props) {
 const [open, setOpen] = useState(false)
 const [filterText, setFilterText] = useState('')
 const [highlighted, setHighlighted] = useState(-1)
 const listboxId = useId()
 const containerRef = useRef<HTMLDivElement>(null)
 const optionRefs = useRef<(HTMLButtonElement | null)[]>([])

 useEffect(() => {
 function handleClickOutside(e: MouseEvent) {
 if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
 setOpen(false)
 setFilterText('')
 setHighlighted(-1)
 }
 }
 document.addEventListener('pointerdown', handleClickOutside)
 return () => document.removeEventListener('pointerdown', handleClickOutside)
 }, [])

 useEffect(() => {
  if (highlighted >= 0) optionRefs.current[highlighted]?.scrollIntoView({ block: 'nearest' })
 }, [highlighted])

 const selectedItems = items.filter((it) => selectedIds.includes(it.id))

 const filteredItems = filterText.trim()
 ? items.filter(
 (it) =>
 it.label.toLowerCase().includes(filterText.toLowerCase()) ||
 (it.sublabel ??'').toLowerCase().includes(filterText.toLowerCase())
 )
 : items

 function toggleItem(id: string) {
 if (selectedIds.includes(id)) {
 onChange(selectedIds.filter((s) => s !== id))
 } else {
 onChange([...selectedIds, id])
 }
 }

 function clearAll() {
 onChange([])
 }

 function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
  if (e.key === 'Escape') {
   setOpen(false)
   setFilterText('')
   setHighlighted(-1)
   return
  }
  if (e.key === 'Enter') {
   const idx = enterToggleIndex(highlighted, filteredItems.length)
   if (idx === null) return
   e.preventDefault()
   toggleItem(filteredItems[idx].id)
   return
  }
  const next = nextHighlightIndex(e.key, highlighted, filteredItems.length)
  if (next === null) return
  e.preventDefault()
  setHighlighted(next)
 }

 return (
 <div ref={containerRef} className="relative">
 <label className="block text-xs font-medium text-foreground mb-1.5">{label}</label>

 {/* Selected chips */}
 {selectedItems.length > 0 && (
 <div className="flex flex-wrap gap-1.5 mb-2">
 {selectedItems.map((it) => (
 <span
 key={it.id}
 className="inline-flex items-center gap-1 text-xs bg-secondary text-primary rounded-full px-2.5 py-0.5 font-medium"
 >
 {it.label}
 <button
 type="button"
 onClick={() => toggleItem(it.id)}
 disabled={disabled}
 className="text-primary/60 hover:text-destructive transition-colors"
 aria-label={`${it.label} entfernen`}
 >
 <X size={10} />
 </button>
 </span>
 ))}
 <button
 type="button"
 onClick={clearAll}
 disabled={disabled}
 className="text-xs text-muted-foreground hover:text-destructive transition-colors px-1"
 >
 Alle entfernen
 </button>
 </div>
 )}

 {/* Dropdown trigger */}
 <button
 type="button"
 disabled={disabled}
 onClick={() => {
 if (!disabled) {
 setOpen((prev) => !prev)
 setFilterText('')
 setHighlighted(-1)
 }
 }}
 className="w-full flex items-center justify-between text-sm px-3 py-2 border border-border rounded bg-card focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary disabled:opacity-60 disabled:cursor-not-allowed"
 >
 <span className="text-muted-foreground text-xs">
 {selectedIds.length === 0
 ? placeholder
 : `${selectedIds.length} ausgewählt`}
 </span>
 <ChevronDown size={14} className={`text-muted-foreground transition-transform ${open ?'rotate-180':''}`} />
 </button>

 {/* Dropdown */}
 {open && (
 <div className="absolute left-0 right-0 top-full mt-1 z-50 bg-card text-foreground border border-border rounded-lg shadow-lg">
 {/* Search */}
 <div className="p-2 border-b border-border">
 <div className="relative">
 <Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"/>
 <input
 type="text"
 value={filterText}
 onChange={(e) => { setFilterText(e.target.value); setHighlighted(-1) }}
 onKeyDown={handleKeyDown}
 role="combobox"
 aria-haspopup="listbox"
 aria-expanded={open}
 aria-controls={listboxId}
 placeholder="Suchen…"
 autoFocus
 className="w-full pl-7 pr-3 py-1.5 text-xs border border-border rounded focus:outline-none focus:ring-1 focus:ring-primary/30 focus:border-primary"
 />
 </div>
 </div>

 {/* Items list */}
 <div id={listboxId} role="listbox" className="overflow-y-auto"style={{ maxHeight:'240px'}}>
 {filteredItems.length === 0 ? (
 <p className="text-xs text-muted-foreground text-center py-4">Keine Einträge</p>
 ) : (
 filteredItems.map((it, i) => {
 const selected = selectedIds.includes(it.id)
 return (
 <button
 key={it.id}
 type="button"
 role="option"
 aria-selected={selected}
 ref={el => { optionRefs.current[i] = el }}
 onClick={() => toggleItem(it.id)}
 onMouseEnter={() => setHighlighted(i)}
 className={`w-full flex items-center gap-3 px-3 text-left transition-colors hover:bg-background ${selected ?'bg-secondary':''} ${i === highlighted ?'ring-2 ring-inset ring-primary/40':''}`}
 style={{ minHeight:'44px'}}
 >
 <div
 className={`w-4 h-4 shrink-0 rounded border flex items-center justify-center transition-colors ${
 selected ?'bg-primary border-primary':'border-border bg-card'
 }`}
 >
 {selected && (
 <svg width="10"height="8"viewBox="0 0 10 8"fill="none">
 <path d="M1 4L3.5 6.5L9 1"stroke="white"strokeWidth="1.5"strokeLinecap="round"strokeLinejoin="round"/>
 </svg>
 )}
 </div>
 <div className="min-w-0">
 <p className="text-xs font-medium text-foreground truncate">{it.label}</p>
 {it.sublabel && (
 <p className="text-[10px] text-muted-foreground truncate">{it.sublabel}</p>
 )}
 </div>
 </button>
 )
 })
 )}
 </div>
 </div>
 )}
 </div>
 )
}
