import { ChevronDown, X } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { Button } from 'shared/ui/button'
import { Input } from 'shared/ui/input'
import { Label } from 'shared/ui/label'

interface AutocompleteInputProps {
  label: string
  value: string
  onValueChange: (value: string) => void
  suggestions: string[]
  placeholder?: string
  disabled?: boolean
}

export const AutocompleteInput: React.FC<AutocompleteInputProps> = ({
  label,
  value,
  onValueChange,
  suggestions,
  placeholder = '',
  disabled = false,
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [filteredSuggestions, setFilteredSuggestions] = useState<string[]>([])
  const [highlightedIndex, setHighlightedIndex] = useState(-1)
  const inputRef = useRef<HTMLInputElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)

  // Фильтруем предложения на основе введенного текста
  useEffect(() => {
    if (value.trim() === '') {
      setFilteredSuggestions(suggestions)
    } else {
      const filtered = suggestions.filter(suggestion =>
        suggestion.toLowerCase().includes(value.toLowerCase())
      )
      setFilteredSuggestions(filtered)
    }
    setHighlightedIndex(-1)
  }, [value, suggestions])

  // Закрытие выпадающего списка при клике вне компонента
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node) &&
        inputRef.current &&
        !inputRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false)
      }
    }

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

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    onValueChange(e.target.value)
    setIsOpen(true)
  }

  const handleSuggestionClick = (suggestion: string) => {
    onValueChange(suggestion)
    setIsOpen(false)
    inputRef.current?.blur()
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!isOpen || filteredSuggestions.length === 0) return

    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault()
        setHighlightedIndex(prev =>
          prev < filteredSuggestions.length - 1 ? prev + 1 : 0
        )
        break
      case 'ArrowUp':
        e.preventDefault()
        setHighlightedIndex(prev =>
          prev > 0 ? prev - 1 : filteredSuggestions.length - 1
        )
        break
      case 'Enter':
        e.preventDefault()
        if (highlightedIndex >= 0) {
          handleSuggestionClick(filteredSuggestions[highlightedIndex])
        }
        break
      case 'Escape':
        setIsOpen(false)
        inputRef.current?.blur()
        break
    }
  }

  const clearValue = () => {
    onValueChange('')
    inputRef.current?.focus()
  }

  return (
    <div className="space-y-2">
      <Label className="text-sm font-medium">{label}</Label>
      <div className="relative">
        <div className="relative">
          <Input
            ref={inputRef}
            value={value}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            onFocus={() => setIsOpen(true)}
            placeholder={placeholder}
            disabled={disabled}
            className="pr-16"
          />
          <div className="absolute inset-y-0 right-0 flex items-center space-x-1 pr-2">
            {value && (
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={clearValue}
                disabled={disabled}
              >
                <X className="h-3 w-3" />
              </Button>
            )}
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="h-6 w-6"
              onClick={() => setIsOpen(!isOpen)}
              disabled={disabled}
            >
              <ChevronDown
                className={`h-3 w-3 transition-transform ${
                  isOpen ? 'rotate-180' : ''
                }`}
              />
            </Button>
          </div>
        </div>

        {/* Выпадающий список предложений */}
        {isOpen && filteredSuggestions.length > 0 && !disabled && (
          <div
            ref={dropdownRef}
            className="absolute z-50 mt-1 max-h-60 w-full overflow-auto rounded-md border bg-popover text-popover-foreground shadow-md"
          >
            {filteredSuggestions.map((suggestion, index) => (
              <div
                key={suggestion}
                className={`cursor-pointer px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground ${
                  index === highlightedIndex
                    ? 'bg-accent text-accent-foreground'
                    : ''
                }`}
                onClick={() => handleSuggestionClick(suggestion)}
                onMouseEnter={() => setHighlightedIndex(index)}
              >
                {suggestion}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default AutocompleteInput
