import { useState, useEffect, useRef } from 'react'
import { de } from '../strings/de'
import { type ColorVariety } from '../api/types'
import FarbschlagImage from './FarbschlagImage'
import './ColorVarietyPicker.css'

interface ColorVarietyPickerProps {
  value: string
  onChange: (id: string) => void
  colorVarieties: ColorVariety[]
}

export default function ColorVarietyPicker({ value, onChange, colorVarieties }: ColorVarietyPickerProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [search, setSearch] = useState('')
  const containerRef = useRef<HTMLDivElement>(null)

  // Close dropdown when clicking outside of it
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // Find currently selected variety
  const selectedVariety = colorVarieties.find((cv) => cv.id === value)

  // Filter varieties by search query
  const filtered = colorVarieties.filter((cv) =>
    cv.name.toLowerCase().includes(search.toLowerCase())
  )

  const handleSelect = (id: string) => {
    onChange(id)
    setIsOpen(false)
    setSearch('')
  }

  return (
    <div className="color-picker-container" ref={containerRef}>
      <button
        type="button"
        className="color-picker-trigger"
        onClick={() => setIsOpen((prev) => !prev)}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
      >
        <span className="color-picker-trigger-content">
          {selectedVariety ? (
            <>
              <FarbschlagImage name={selectedVariety.name} size={24} />
              <span className="color-picker-trigger-name">{selectedVariety.name}</span>
            </>
          ) : (
            <span className="color-picker-placeholder">{de.pages.gerbils.form.none}</span>
          )}
        </span>
        <span className="color-picker-caret">▾</span>
      </button>

      {isOpen && (
        <div className="color-picker-dropdown">
          <div className="color-picker-search-wrapper">
            <input
              type="text"
              className="color-picker-search"
              placeholder="Farbschlag suchen..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              autoFocus
            />
          </div>
          <div className="color-picker-options" role="listbox">
            <button
              type="button"
              className={`color-picker-option ${!value ? 'color-picker-option--selected' : ''}`}
              onClick={() => handleSelect('')}
              role="option"
              aria-selected={!value}
            >
              <div className="color-picker-option-image-placeholder" />
              <span className="color-picker-option-name">{de.pages.gerbils.form.none}</span>
            </button>
            {filtered.map((cv) => {
              const isSelected = cv.id === value
              return (
                <button
                  key={cv.id}
                  type="button"
                  className={`color-picker-option ${isSelected ? 'color-picker-option--selected' : ''}`}
                  onClick={() => handleSelect(cv.id)}
                  role="option"
                  aria-selected={isSelected}
                >
                  <div className="color-picker-option-image-wrapper">
                    <FarbschlagImage name={cv.name} size={24} />
                  </div>
                  <span className="color-picker-option-name">{cv.name}</span>
                </button>
              )
            })}
            {filtered.length === 0 && (
              <div className="color-picker-no-results">
                Keine Farbschläge gefunden
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
