"use client"

import { useState, useRef, useEffect } from "react"
import { Check,  X } from "lucide-react"
import { cn } from "@/lib/utils"

interface Option {
  id: string
  name: string
  icon?: React.ReactNode
}

interface CustomMultiSelectProps {
  options: Option[]
  selected: string[]
  onValueChange: (values: string[]) => void
  placeholder?: string
  className?: string
}

export function CustomMultiSelect({
  options,
  selected,
  onValueChange,
  placeholder = "Select values...",
  className
}: CustomMultiSelectProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [searchTerm, setSearchTerm] = useState("")
  const dropdownRef = useRef<HTMLDivElement>(null)

  const filteredOptions = options.filter(option =>
    option.name.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const selectedOptions = options.filter(option => selected.includes(option.id))

  const toggleOption = (optionId: string) => {
    if (selected.includes(optionId)) {
      onValueChange(selected.filter(item => item !== optionId))
    } else {
      onValueChange([...selected, optionId])
    }
  }

  const removeOption = (optionId: string) => {
    onValueChange(selected.filter(item => item !== optionId))
  }

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  return (
    <div className={cn("relative", className)} ref={dropdownRef}>
      {/* Main Input Container */}
      <div 
        className={cn(
          "min-h-[10px] w-full rounded-sm border bg-background px-2 py-2 cursor-pointer transition-colors",
          isOpen ? "border-primary" : "border-gray-200 hover:border-gray-300"
        )}
        onClick={() => setIsOpen(!isOpen)}
      >
        <div className="flex flex-wrap items-center gap-2">
          {/* Selected Tags */}
          {selectedOptions.map((option) => (
            <div
              key={option.id}
              className="flex items-center gap-1 bg-background rounded rounded-md  px-0.5 py-0.5 text-xs border border-primary"
            >
              {option.icon && <span className="text-sm">{option.icon}</span>}
              <span className="ml-2 font-medium">{option.name}</span>
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  removeOption(option.id)
                }}
                className=" ml-px"
              >
                <X className="w-3 h-3" />
              </button>
            </div>
          ))}
          
          {/* Placeholder/Search Input */}
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder={placeholder}
            className="flex-1 min-w-[120px] outline-none bg-transparent placeholder:text-sm  text-gray-600 placeholder-gray-400"
            onFocus={() => setIsOpen(true)}
            onClick={(e) => {
              e.stopPropagation()
              setIsOpen(true)
            }}
          />
          
          {/* Clear All Button */}
          {selectedOptions.length > 0 && (
            <button
              onClick={(e) => {
                e.stopPropagation()
                onValueChange([])
              }}
              className="text-gray-400 hover:text-gray-600 p-1"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Dropdown */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-background border border-primary rounded-lg shadow-lg z-50 max-h-70 overflow-y-auto">
          <div className="p-2 space-y-1">
            {filteredOptions.length === 0 ? (
              <div className="px-3 py-2 text-sm text-gray-500">No options found</div>
            ) : (
              filteredOptions.map((option) => {
                const isSelected = selected.includes(option.id)
                return (
                  <div
                    key={option.id}
                    className={cn(
                      "flex items-center gap-2  px-3 py-2 rounded cursor-pointer transition-colors",
                      isSelected 
                        ? "bg-primary/10 text-primary" 
                        : "hover:bg-primary/20"
                    )}
                    onClick={() => toggleOption(option.id)}
                  >
                    {isSelected && (
                      <Check className="w-5 h-5 stroke-4 text-primary flex-shrink-0" />
                    )}
                    {/* {!isSelected && <div className="w-4 h-4 flex-shrink-0" />} */}
                    
                    {option.icon && (
                      <span className="text-sm flex-shrink-0">{option.icon}</span>
                    )}
                    
                    <span className="text-sm font-medium flex-1">{option.name}</span>
                  </div>
                )
              })
            )}
          </div>
        </div>
      )}
    </div>
  )
}