import { TextInput } from 'flowbite-react'
import React, { useState, useRef, useEffect } from 'react'
import formTheme from '../themes/form'

export interface MultiSelectOption {
  label: string
  value: number
}

export interface MultiSelectProps {
  options: MultiSelectOption[]
  value: (number | undefined)[]
  placeholder?: string
  label?: string
  disabled?: boolean
  className?: string
  onChange: (value: (number | undefined)[]) => void
  onScrollBottom?: () => void
}

const MultiSelect: React.FC<MultiSelectProps> = ({
  options,
  value,
  onChange,
  onScrollBottom,
  placeholder = 'Select options',
  label,
  disabled = false,
  className = '',
}) => {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement | null>(null)
  const [searchValue, setSearchValue] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')

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

  // debounce search input
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(searchValue), 250)
    return () => clearTimeout(t)
  }, [searchValue])

  const handleSelect = (optionValue: number) => {
    if (value?.includes(optionValue)) {
      onChange(value?.filter((v) => v !== optionValue))
    } else {
      onChange([...value, optionValue])
    }
  }

  // filter options by debounced search
  const filteredOptions =
    debouncedSearch.trim().length > 0
      ? options.filter((opt) =>
          opt.label.toLowerCase().includes(debouncedSearch.toLowerCase()),
        )
      : options

  const selectedOptions = options.filter((opt) => value.includes(opt.value))

  return (
    <div className={`relative w-full ${className}`} ref={ref}>
      {label && (
        <label className="block mb-1 text-sm font-medium text-gray-700">
          {label}
        </label>
      )}
      <button
        type="button"
        className={`w-full flex justify-between items-center border rounded-lg px-3 py-2 text-gray-900 focus:ring focus:ring-primary focus:border-primary bg-slate-50 disabled:cursor-not-allowed focus:outline-0 ${open ? 'ring ring-primary border-blue-500' : 'border-gray-300'}`}
        onClick={() => setOpen((prev) => !prev)}
        disabled={disabled}
      >
        <span
          className={`truncate text-sm ${selectedOptions.length === 0 ? 'text-gray-400' : ''}`}
        >
          {selectedOptions.length === 0
            ? placeholder
            : `${selectedOptions.length} selected`}
        </span>
        <svg
          className={`w-4 h-4 ml-2 transition-transform ${open ? 'rotate-180' : ''}`}
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>

      {open && (
        <div
          className="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-auto animate-fade-in"
          onScroll={(e) => {
            const target = e.currentTarget
            if (
              target.scrollTop + target.clientHeight >=
              target.scrollHeight - 10
            ) {
              onScrollBottom?.()
            }
          }}
        >
          {/* Search input */}
          <TextInput
            ref={inputRef}
            type="text"
            theme={formTheme.textInput}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="Search..."
            className="w-full px-3 py-2 text-sm  rounded focus:outline-none"
            onKeyDown={(e) => {
              if (e.key === 'Escape') {
                setSearchValue('')
              }
            }}
          />

          {filteredOptions?.length === 0 ? (
            <div className="px-4 py-2 text-gray-400">No options</div>
          ) : (
            filteredOptions.map((opt) => (
              <button
                key={opt.value}
                type="button"
                className={`flex items-center text-sm w-full px-4 py-2 text-left hover:bg-blue-50 focus:bg-blue-100 focus:outline-0 ${value.includes(opt.value) ? 'bg-blue-100 text-blue-700' : ''}`}
                onClick={() => handleSelect(opt.value)}
                disabled={disabled}
              >
                <span className="flex-1">{opt.label}</span>
                {value.includes(opt.value) && (
                  <svg
                    className="w-4 h-4 text-blue-600 ml-2"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                )}
              </button>
            ))
          )}
        </div>
      )}

      {/* Selected labels below the select */}
      {selectedOptions.length > 0 && (
        <div className="flex flex-wrap gap-2 mt-4">
          {selectedOptions.map((opt) => (
            <span
              key={opt.value}
              className="inline-flex items-center px-2 py-1 rounded-full bg-gradient-to-r from-gray-100 to-gray-200 text-xs font-medium"
            >
              {opt.label}
              <button
                type="button"
                className="ml-1 rounded-full hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-red-400"
                onClick={() => handleSelect(opt.value)}
                aria-label={`Remove ${opt.label}`}
                disabled={disabled}
              >
                <svg
                  className="w-3 h-3 text-red-700"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </span>
          ))}
        </div>
      )}
    </div>
  )
}

export default MultiSelect
