'use client'

import { useState, useEffect, useRef } from 'react'
import { ProductModule } from '@/lib/types'
import { Plus, Search } from 'lucide-react'

interface ModulePopoverProps {
  assignedModules: ProductModule[]
  allModules: ProductModule[]
  onAddModule: (module: ProductModule) => void
}

export function ModulePopover({ assignedModules, allModules, onAddModule }: ModulePopoverProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [search, setSearch] = useState('')
  const popoverRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  // Filter modules that are not already assigned to this product
  // We match by name to treat identical modules across products as the same entity
  const availableModules = allModules.filter(m => {
    const isAssigned = assignedModules.some(am => am.name.toLowerCase() === m.name.toLowerCase())
    const matchesSearch = m.name.toLowerCase().includes(search.toLowerCase()) || 
                          (m.description && m.description.toLowerCase().includes(search.toLowerCase()))
    return !isAssigned && matchesSearch
  })

  // Deduplicate available modules by name to show a clean list
  const uniqueAvailableModules: ProductModule[] = []
  const seenNames = new Set<string>()
  for (const m of availableModules) {
    const nameKey = m.name.toLowerCase()
    if (!seenNames.has(nameKey)) {
      seenNames.add(nameKey)
      uniqueAvailableModules.push(m)
    }
  }

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus()
    }
  }, [isOpen])

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (popoverRef.current && !popoverRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen])

  return (
    <div className="relative inline-block" ref={popoverRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-primary/10 text-primary border border-primary/20 hover:bg-primary hover:text-black rounded-lg transition-all"
      >
        <Plus className="w-3.5 h-3.5" />
        Modul hinzufügen
      </button>

      {isOpen && (
        <div className="absolute left-0 mt-2 z-50 w-72 bg-slate-900 border border-white/10 rounded-xl shadow-2xl p-3 space-y-3">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-slate-400" />
            <input
              ref={inputRef}
              type="text"
              placeholder="Modul suchen..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full bg-white/5 border border-white/10 rounded-lg pl-9 pr-3 py-1.5 text-xs text-white placeholder-slate-400 outline-none focus:border-primary/50 transition-colors"
            />
          </div>

          <div className="max-h-60 overflow-y-auto space-y-1 pr-1 custom-scrollbar">
            {uniqueAvailableModules.length > 0 ? (
              uniqueAvailableModules.map((mod) => (
                <button
                  key={mod.id}
                  onClick={() => {
                    onAddModule(mod)
                    setIsOpen(false)
                    setSearch('')
                  }}
                  className="w-full text-left p-2 hover:bg-white/5 rounded-lg transition-colors group"
                >
                  <div className="font-medium text-xs text-white group-hover:text-primary transition-colors">
                    {mod.name}
                  </div>
                  {mod.description && (
                    <div className="text-[10px] text-slate-400 line-clamp-1 mt-0.5">
                      {mod.description}
                    </div>
                  )}
                  <div className="text-[10px] text-primary font-mono mt-1">
                    {new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(mod.price)}
                  </div>
                </button>
              ))
            ) : (
              <div className="text-[11px] text-slate-400 text-center py-4">
                Keine passenden Module gefunden.
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
