'use client'

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

interface DependencyPopoverProps {
  currentProductId: string
  assignedIds: string[]
  allProducts: Product[]
  allModules: ProductModule[]
  onAddDependency: (id: string) => void
}

export function DependencyPopover({
  currentProductId,
  assignedIds,
  allProducts,
  allModules,
  onAddDependency
}: DependencyPopoverProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [search, setSearch] = useState('')
  const popoverRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  // Filter out the current product, and items already assigned
  const otherProducts = allProducts.filter(p => p.id !== currentProductId && !assignedIds.includes(p.id))
  const otherModules = allModules.filter(m => m.product_id !== currentProductId && !assignedIds.includes(m.id))

  // Apply search
  const filteredProducts = otherProducts.filter(p => p.name.toLowerCase().includes(search.toLowerCase()))
  const filteredModules = otherModules.filter(m => m.name.toLowerCase().includes(search.toLowerCase()))

  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="p-1 hover:bg-white/10 rounded transition-all text-slate-400 hover:text-white"
        title="Abhängigkeit hinzufügen"
      >
        <Plus className="w-3.5 h-3.5" />
      </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="Suchen nach Produkt/Modul..."
              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-2 pr-1 custom-scrollbar">
            {filteredProducts.length > 0 && (
              <div className="space-y-1">
                <span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider px-1">Produkte</span>
                {filteredProducts.map(p => (
                  <button
                    key={p.id}
                    onClick={() => {
                      onAddDependency(p.id)
                      setIsOpen(false)
                      setSearch('')
                    }}
                    className="w-full text-left p-1.5 hover:bg-white/5 rounded-lg transition-colors flex items-center gap-2 group"
                  >
                    <Package className="w-3 h-3 text-slate-500 group-hover:text-primary transition-colors" />
                    <span className="text-xs text-white group-hover:text-primary transition-colors">{p.name}</span>
                  </button>
                ))}
              </div>
            )}

            {filteredModules.length > 0 && (
              <div className="space-y-1">
                <span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider px-1">Module</span>
                {filteredModules.map(m => (
                  <button
                    key={m.id}
                    onClick={() => {
                      onAddDependency(m.id)
                      setIsOpen(false)
                      setSearch('')
                    }}
                    className="w-full text-left p-1.5 hover:bg-white/5 rounded-lg transition-colors flex items-center gap-2 group"
                  >
                    <Layers className="w-3 h-3 text-slate-500 group-hover:text-primary transition-colors" />
                    <span className="text-xs text-white group-hover:text-primary transition-colors">{m.name}</span>
                  </button>
                ))}
              </div>
            )}

            {filteredProducts.length === 0 && filteredModules.length === 0 && (
              <div className="text-[11px] text-slate-400 text-center py-4">
                Keine Ergebnisse gefunden.
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
